从 JSON/String 文件中获取特定的 JSON 属性

我正在向服务器发送 POST 请求。服务器使用以下 (JSON) 进行响应:


{"data":[      

{

  "password":"1234578566",

  "status":"processing"

}

],

 "status":200

}

这是我的 POST 方法:


public static void sendPostRequest(String conversion) throws IOException, AuthenticationException {

CloseableHttpClient client = HttpClients.createDefault();

HttpPost httpPost = new HttpPost("https://url.com");


httpPost.setEntity(new StringEntity(conversion));

UsernamePasswordCredentials credentials =

        new UsernamePasswordCredentials("username", "password");

httpPost.addHeader(new BasicScheme().authenticate(credentials, httpPost, null));


httpPost.setHeader("Accept", "application/json");

httpPost.setHeader("Content-type", "application/json");


HttpResponse response = client.execute(httpPost);


String data = EntityUtils.toString(response.getEntity());


client.close();

//     System.out.println(data); 

请注意,字符串“data”是响应上述 JSON 数据的服务器。现在,我试图从数据中获取密码属性。


public static void getValue(String data) throws ParseException {

    JSONObject object = (JSONObject) new JSONParser().parse(data);


    JSONArray array = (JSONArray) object.get("data");

    JSONObject attribute = (JSONObject) array.get(0);

    JSONObject userData = (JSONObject) attribute.get("password");

    String result =  userData.toString();


    System.out.println(result);

}


Exception in thread "main" Unexpected character (T) at position 0.

at org.json.simple.parser.Yylex.yylex(Unknown Source)

at org.json.simple.parser.JSONParser.nextToken(Unknown Source)

at org.json.simple.parser.JSONParser.parse(Unknown Source)

at org.json.simple.parser.JSONParser.parse(Unknown Source)

at org.json.simple.parser.JSONParser.parse(Unknown Source)

我收到此异常,但我想知道为什么?曾试图在这里和那里改变,但没有成功。


这些是我的进口:


import org.json.simple.JSONObject;

import org.json.simple.JSONArray;

import org.json.simple.parser.ParseException;

import org.json.simple.parser.JSONParser;

谢谢你。


郎朗坤
浏览 222回答 1
1回答

森栏

看起来您正在错误地解析响应。这里有两件事要做。1) 确保从响应中正确获取 JSON 数据。您可以点击此链接从 HTTP 响应中获取JSON 对象,以从您的响应中获取字符串化的 JSON 数据。2) 使用您的 JSON 以从中获取特定值。您的getValue()方法只需稍加修改即可用于该目的。我对您的方法进行了一些更改,这里是相同的更新代码:public static void getValue(String data) {        try {        JSONObject responseObject = new JSONObject(data);               JSONArray jsonArray = (JSONArray) responseObject.get("data");        JSONObject jsonObject = (JSONObject) jsonArray.get(0);        String result  = jsonObject.getString("password");        System.out.println(result);        } catch (JSONException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }我已经用你的数据对其进行了测试,它按预期工作,通过控制台打印 1234578566。注意:我在这里使用了 org.json lib 而不是简单的 json。希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java