为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

郎朗坤 2021-07-12 12:11:37
我正在向服务器发送 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;谢谢你。
查看完整描述

1 回答

?
森栏

TA贡献1810条经验 获得超5个赞

看起来您正在错误地解析响应。这里有两件事要做。


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。


希望这可以帮助。


查看完整回答
反对 回复 2021-07-14
  • 1 回答
  • 0 关注
  • 221 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信