简体   繁体   中英

How to parse below JSON response?

{
    "status": true,
    "data": {
        "1": "Business People",
        "2": "Actors",
        "3": "Musicians",
        "4": "Sports People",
        "5": "Artists",
        "6": "Politicians"
    },
    "message": "Get data successfully."
}

I want to parse the above json.

Thanks in Advance

I think it's not a good practice to keep numbers as key in your object, I advise you to use a JsonArray

{
 "status":true,
 "message":"Get data successfully.",
 "data":[ "Business People", "Actors", "Musicians", "Sports People", "Artists" 
 ,"Politicians"]
}

and then use JsonArray to parse data

Change your data to JSONArray as a set of JSONObject to perform dynamic job

 JSONObject json = new JSONObject(your_string)
 JSONArray  data = json.getJsonArray("data");

 for(int i = 0;i<data.length();i++)
  {
   JSONObject item = data.getJSONObject(i);
   String itemString = item.getString(Integer.parseInt(i+1));
 /// do whatever you want ie : add itemString to a list
  }

You may use handy service that generates you java model.

Then just use Gson to serialize-deserialize json.

However in your case that "1", "2", "3" etc may be fixed parameters, or dynamic Map.

I suggest using Klaxon to parse the JSON https://github.com/cbeust/klaxon

Really easy usage:

Klaxon().parse<yourClass>(yourJsonAsString)

where yourClass is a data class with your parsing needs. See Klaxon documentation with for each of your needs. Comment if you need help.

Visit this website https://quicktype.io/ it will help you in the creation of java models.

Now serialize and deserialize JSON by using GSON.

Add the following dependency implementation 'com.google.code.gson:gson:2.8.5'

Here is an example:

public Car fromJson(){

String json = "{\"brand\":\"Jeep\", \"doors\": 3}";
Gson gson = new Gson();
Car car = gson.fromJson(json, Car.class);
return car;

}

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