简体   繁体   English

当响应不包含头信息时,如何解析json响应

[英]How to parse json response, when the response does not contain header information

I am trying to parse a json response so that i can get elements out of an object, getting the following error A JSONObject text must begin with '{' at 1 [character 2 line 1] 我试图解析一个json响应,以便我可以从一个对象中获取元素,得到以下错误JSONObject文本必须以'{'at 1 [character 2 line 1]开头

public static  String parseJsonResponse(String json){
    String uId ="";

    try {
         JSONObject jsonObj = new JSONObject(json);
         // String fname = jsonObj.getString("fname");
         //String lname = jsonObj.getString("lname");
         String aId = jsonObj.getString("id");
         uId = aId; 
     } catch (Exception e) {
         e.printStackTrace();
     }
    return uId;
}

Here is json response using postman you will notice there is no header 这里是使用邮递员的json回复你会注意到没有标题

[
    {
        "id": "emplo000000000043567",
        "displayName": "Tester, user1",
           },
    {
        "id": "emplo000000000035386",
        "displayName": "Tester, User2",

    }
]

Like the comment above mentioned, that is a JSON array so it needs to be parsed as a JSON array and not a JSON object. 与上面提到的注释一样,这是一个JSON数组,因此需要将其解析为JSON数组而不是JSON对象。 Just use the JSONArray equivalent provided in the library you are using. 只需使用您正在使用的库中提供的JSONArray等效项。

On another note, with the JSON response above, parsing this as a JSON array would fail since the format is incorrect. 另一方面,通过上面的JSON响应,将其解析为JSON数组将失败,因为格式不正确。 Notice the comma at the end of every last keyvalue in each object. 请注意每个对象中每个最后一个键值末尾的逗号。 That would cause the parser to fail when attempting to parse that as a JSON array. 这会导致解析器在尝试将其解析为JSON数组时失败。 If that was your mistake when you were writing the snippet here then ignore this paragraph. 如果您在此处编写代码段时错误,则忽略此段落。 Else if that was the actual JSON response then I guess you need to make a new question... over at the Postman forum. 否则,如果这是真正的JSON响应,那么我想你需要在Postman论坛上提出一个新问题。

There are several ideas for this case. 这种情况有几个想法。 Here is mine. 这是我的。

  1. With a json simple library [link] . 使用json简单库[link]

You can simply change your library to a json simple library which has a parser class for a json string then use an instanceof method for detection before processing a json object. 您可以简单地将库更改为json简单库,该库具有json字符串的解析器类,然后在处理json对象之前使用instanceof方法进行检测。

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public static  String parseJsonResponse(String json){
    String uId ="";

    try {
        JSONParser parser = new JSONParser();
        Object whichone = parser.parse(json);

        if(whichone instanceof JSONObject)
        {
            JSONObject jsonObj = (JSONObject)whichone;
             // String fname = jsonObj.getString("fname");
             //String lname = jsonObj.getString("lname");
            if(jsonObj.containsKey("id"))
                uId = (String)jsonObj.get("id");
       }
        else if(whichone instanceof JSONArray)
        {
            JSONArray jsonArr = (JSONArray)whichone;
            JSONObject jsonObj = null;

            for(int i = 0; i < jsonArr.size(); i++)
            {
                jsonObj = (JSONObject) jsonArr.get(i);
                if(jsonObj.containsKey("id"))
                {
                    uId = (String)jsonObj.get("id");
                    System.out.println(uId);
                }

            }
        }
        else if(whichone instanceof String)
        {
            System.out.println("1?????" + whichone.toString());
        }
        else
        {
            System.out.println("2?????" + whichone.toString());
        }

     } catch (Exception e) {
         e.printStackTrace();
     }
    return uId;
}
  1. Detect the object type from a json excetpion. 从json excetpion检测对象类型。 You can catch it whether some string is a json object or json array during exception handling. 在异常处理期间,您可以捕获一些字符串是json对象还是json数组。
import org.json.JSONArray;
import org.json.JSONObject;

public static  String parseJsonResponse(String json){
    String uId ="";

    try {
        JSONObject jobj =  new JSONObject(json);

        if(jobj.has("id"))
            uId = jobj.getString("id");

        System.out.println(uId);

     } catch (org.json.JSONException e) {
         //e.printStackTrace();

         JSONArray jsonArr = new JSONArray(json);
         JSONObject jsonObj = null;

         for(int i = 0; i < jsonArr.length(); i++)
            {
                jsonObj = jsonArr.getJSONObject(i);
                if(jsonObj.has("id"))
                {
                    uId = (String)jsonObj.get("id");
                    System.out.println(uId);
                }

            }
     }
    return uId;
}
  1. With a java work. 用java工作。

You can find it whether it's a json object or array after parsing a first character. 在解析第一个字符后,您可以找到它是json对象还是数组。 (I think it will work...) (我认为它会起作用......)

import org.json.JSONArray;
import org.json.JSONObject;
public static  String parseJsonResponse(String json){
    String uId ="";

    boolean isJobj = json.charAt(0) == '[';

    if(!isJobj) {
        JSONObject jobj =  new JSONObject(json);

        if(jobj.has("id"))
            uId = jobj.getString("id");

        System.out.println(uId);

     } else {
         JSONArray jsonArr = new JSONArray(json);
         JSONObject jsonObj = null;

         for(int i = 0; i < jsonArr.length(); i++)
            {
                jsonObj = jsonArr.getJSONObject(i);
                if(jsonObj.has("id"))
                {
                    uId = (String)jsonObj.get("id");
                    System.out.println(uId);
                }

            }
     }
    return uId;
}

Have a good day.. 祝你有美好的一天..

First, Your json format is wrong. 首先,你的json格式是错误的。 The correct json format would be: 正确的json格式是:

[
    {
        "id": "emplo000000000043567",
        "displayName": "Tester, user1"
    },
    {
        "id": "emplo000000000035386",
        "displayName": "Tester, User2"
    }
]

Now, 现在,

  1. Your Response is JSON Array. 您的响应是JSON数组。 So first assign parsed object into JSON Array as JSONArray array = (JSONArray) obj ; 所以首先将解析后的对象分配为JSON数组,作为JSONArray array =(JSONArray)obj ;
  2. this JSON Array consists of two JSON Object so traverse the array, get each JSON Object and print/return key/value pair whatever you want. 此JSON数组由两个JSON对象组成,因此遍历数组,获取每个JSON对象并打印/返回键/值对,无论您想要什么。

A sample code is given below:(see the logic) 下面给出了一个示例代码:(参见逻辑)

public static void parseJsonResponse(String json)
            throws JsonParseException, JsonMappingException, IOException, ParseException {
        String aId ="";
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONArray array = (JSONArray) obj;
        for(int i=0;i<array.size();i++)
        {
            JSONObject jsonObject = (JSONObject) array.get(i);
            aId = (String) jsonObject.get("id");
            System.out.println(aId);
        }

    }

Note: I have used json-simple java library here. 注意:我在这里使用了json-simple java库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM