REST and JSON - converting string to JSON array

前端 未结 3 710
醉梦人生
醉梦人生 2021-01-19 03:53

I\'m new to JSON and REST. I\'m working with a server that returns strings like these:

[{\"username\":\"Hello\",\"email\":\"hello@email.com\",\"credits\":\"1         


        
相关标签:
3条回答
  • 2021-01-19 04:00
    • use GSON to format the string as JsonArray
    • then traverse the JsonArray to get the values

    the code sample

    String json = "[{\"username\":\"Hello\",\"email\":\"hello@email.com\",\"credits\":\"100\",\"twitter_username\":\"\"},{\"username\":\"Goodbye\",\"email\":\"goodbye@email.com\",\"credits\":\"0\",\"twitter_username\":\"\"}]";
    JsonArray jArray = new JsonParser().parse(json).getAsJsonArray();
    for (int i=0;i<jArray.size();i++) {
        JsonObject jsonObject = jArray.get(i).getAsJsonObject();
        System.out.println(jsonObject.get("username"));
        System.out.println(jsonObject.get("email"));
        System.out.println(jsonObject.get("credits"));
        System.out.println(jsonObject.get("twitter_username"));
        System.out.println("*********");
    }
    
    0 讨论(0)
  • 2021-01-19 04:06

    I have used org.json.simple.JSONObject and org.json.simple.JSONArray, and I hope net.sf.json.JSONArray also work same.

    You should put following string format for output (JSONArray array = new JSONArray(output); )

     {"YOUR_ARRAY_NAME": [{"username":"Hello","email":"hello@email.com","credits":"100","twitter_username":""},{"username":"Goodbye","email":"goodbye@email.com","credits":"0","twitter_username":""}]}
    

    Now this is String representation of JSONArray.

    0 讨论(0)
  • 2021-01-19 04:22

    I am using gson library to manipulate json. You can download gson from here. It is a very good library to handle json. Create json parser first, it will parse the json string:

    JsonParser parser = new JsonParser();
    

    now initialize an empty json array

    JsonArray jArray = new JsonArray();
    

    Now use the parser to create json array

    jArray = parser.parse(outputString).getAsJsonArray();
    
    0 讨论(0)
提交回复
热议问题