英文:
How to parse this type of json using GSON?
问题
需要将JSON解析为Java对象,如何使用逗号分隔的字符串创建一个列表作为对象示例在下面的代码中感兴趣。
{
"following": [
],
"website": "",
"name": "Bala",
"gender": "",
"interest": [
"Cricket",
"FootBall",
"BasketBall"
],
"isConfirmed": true,
"posturl": [
"https://www.google.com",
"https://www.google.com"
],
"age": ""
}
英文:
Need to parse the JSON to Java Object, how to create a list using comma-separated string as an object example Intrest in the code below.
{
"following": [
],
"website": "",
"name": "Bala",
"gender": "",
"interest": [
"Cricket",
"FootBall",
"BasketBall"
],
"isConfirmed": true,
"posturl": [
"https://www.google.com",
"https://www.google.com"
],
"age": ""
}
答案1
得分: 0
interest
在JSON中不是逗号分隔的字符串。它是一个数组。您可以将其映射到Java对象中的List<String>
类型。
英文:
interest
in the json is not a comma separated String. It is an array. You can map it to List<String>
type in java object.
答案2
得分: 0
Gson gson = new GsonBuilder().create();
JsonObject jsonObject = gson.fromJson(String YourJSONObject, JsonObject.class);
## 解析 JSON 对象 ##
JsonArray interestarray = jsonObject.getAsJsonArray("interest");
## 将 JSONArray 元素存储到 ArrayList 中 ##
List<String> list = new ArrayList<>();
for (JsonElement interest : interestarray) {
list.add(interest.getAsString());
}
英文:
Gson gson = new GsonBuilder().create();
JsonObject jsonObject = gson.fromJson(String YourJSONObject, JsonObject.class);
## Parsing JSON object ##
JsonArray interestarray = jsonObject.getAsJsonArray("interest");
## Storing JSONArray elements into Arraylist ##
List<String> list=new ArrayList<>();
for(JsonElement interest:interestarray){
list.add(interest.getAsString());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论