简体   繁体   中英

Convert JSON String to JSON Array

Hello i call a service if it contains multiple objects it make list but when it contain only one object it return a single object not a list [] are missing , actually i want to convert them into java class using gson but in case of single exception it throw exception but when it contain list it work fine i actually need to convert my single gSON string to array ,please help me ..here is the string

    {
   "response":{
      "projects":{
         "project":{
            "ixWorkflow":1,
            "sEmail":"j.a@loxvo.com",
            "sPhone":"",
            "ixProject":2,
            "ixPersonOwner":2,
            "fDeleted":false,
            "sProject":"Project Default",
            "fInbox":true,
            "sPersonOwner":"junaid"
         }
      }
   }
}

i want it to be like same as

   {
   "response":{
      "projects":{
         "project":[
            {
               "ixWorkflow":1,
               "sEmail":"j.a@loxvo.com",
               "sPhone":"",
               "ixProject":6,
               "ixPersonOwner":2,
               "fDeleted":false,
               "sProject":"project 2",
               "fInbox":false,
               "sPersonOwner":"junaid"
            },
            {
               "ixWorkflow":1,
               "sEmail":"j.a@loxvo.com",
               "sPhone":"",
               "ixProject":2,
               "ixPersonOwner":2,
               "fDeleted":false,
               "sProject":"Project Default",
               "fInbox":true,
               "sPersonOwner":"junaid"
            }
         ]
      }
   }
}

With reference to https://stackoverflow.com/a/7284813/1105291

Please try below code before you pass json to Gson for object conversion, and please let me know if you get any error. Only posibility that I can see is exception at if.

    JSONObject jsonObject = new JSONObject(responseString);
    JSONObject projectsJsonObject = jsonObject.getJSONObject("response").getJSONObject("projects"); 
    if(projectsJsonObject.getJSONArray("project") == null)
    {
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(projectsJsonObject.getJSONObject("project"));
        projectsJsonObject.put("project", jsonArray);

    }
    //Pass jsonObject to Gson

Use Google Gson

JsonParser parser = new JsonParser();
JsonObject o = (JsonObject)parser.parse("{\"a\": \"A\"}");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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