[英]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.我想解析上面的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我认为将数字作为对象中的键不是一个好习惯,我建议您使用 JsonArray
{
"status":true,
"message":"Get data successfully.",
"data":[ "Business People", "Actors", "Musicians", "Sports People", "Artists"
,"Politicians"]
}
and then use JsonArray to parse data然后使用 JsonArray 解析数据
Change your data to JSONArray as a set of JSONObject to perform dynamic job将您的数据更改为 JSONArray 作为一组 JSONObject 以执行动态作业
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.您可以使用方便的服务来生成您的 Java 模型。
Then just use Gson to serialize-deserialize json.然后只需使用 Gson 对 json 进行序列化-反序列化。
However in your case that "1", "2", "3" etc may be fixed parameters, or dynamic Map.但是,在您的情况下,“1”、“2”、“3”等可能是固定参数或动态地图。
I suggest using Klaxon to parse the JSON https://github.com/cbeust/klaxon我建议使用 Klaxon 来解析 JSON https://github.com/cbeust/klaxon
Really easy usage:使用非常简单:
Klaxon().parse<yourClass>(yourJsonAsString)
where yourClass is a data class with your parsing needs.其中 yourClass 是具有解析需求的数据类。 See Klaxon documentation with for each of your needs.
请参阅 Klaxon 文档以了解您的每个需求。 Comment if you need help.
如果您需要帮助,请发表评论。
Visit this website https://quicktype.io/ it will help you in the creation of java models.访问此网站https://quicktype.io/它将帮助您创建 Java 模型。
Now serialize and deserialize JSON by using GSON.现在使用 GSON 序列化和反序列化 JSON。
Add the following dependency implementation 'com.google.code.gson:gson:2.8.5'添加以下依赖项实现 'com.google.code.gson:gson:2.8.5'
Here is an example:下面是一个例子:
public Car fromJson(){公共汽车 fromJson(){
String json = "{\"brand\":\"Jeep\", \"doors\": 3}";
Gson gson = new Gson();
Car car = gson.fromJson(json, Car.class);
return car;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.