如何使用GSON解析这种类型的JSON?

huangapple go评论73阅读模式
英文:

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(&quot;interest&quot;);


## Storing JSONArray elements into Arraylist ##
List&lt;String&gt; list=new ArrayList&lt;&gt;();
for(JsonElement interest:interestarray){
list.add(interest.getAsString());
}

huangapple
  • 本文由 发表于 2020年8月10日 02:04:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63329666.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定