Java:从 Json 字符串中获取值(Set<String>)

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

Java: Get value from a Json string (Set<String>)

问题

  1. 我正在使用这个方法,它返回一个`Set<String>`,但实际上我得到的是一个像这样的Json字符串:

[
{
"id":"Id1"
},
{
"id":"Id2",
"title":"anyTitle"
}
]

  1. 我的目标是获取键"id"的值。我还创建了一个Java Bean来映射数据:
  2. ```java
  3. public class Data {
  4. private String id;
  5. private String title;
  6. public String getId() {
  7. return id;
  8. }
  9. public void setId(String id) {
  10. this.id = id;
  11. }
  12. public String getTitle() {
  13. return title;
  14. }
  15. public void setTitle(String title) {
  16. this.title = title;
  17. }
  18. }

我尝试使用gson解析,但我得到的只是一个错误:无法将'java.util.LinkedHashMap$LinkedKeyIterator'转换为'com.google.gson.stream.JsonReader'。

所以,显然我做错了什么:

  1. Set<String> availableData = getData(); // 这个方法返回一个json字符串
  2. Iterator<String> itr = availableData.iterator();
  3. while (itr.hasNext()) {
  4. Gson gson = new Gson();
  5. JsonParser parser = new JsonParser();
  6. JsonObject object = (JsonObject) parser.parse(itr.next());
  7. Data data = gson.fromJson(object, Data.class);
  8. }

更新:实际错误是:类型不匹配,无法将'com.google.common.collect.Maps$TransformedEntriesMap'分配给'java.lang.String'。

  1. <details>
  2. <summary>英文:</summary>
  3. I&#39;m using this method that returns a `Set&lt;String&gt;` but in fact what I got is a Json string like this

[
{
"id":"Id1"
},
{
"id":"Id2",
"title":"anyTitle"
}
]

  1. My goal is to get the value of key &quot;id&quot;. I&#39;ve also made a java bean to map the data:
  2. public class Data {
  3. private String id;
  4. private String title;
  5. public String getId() {
  6. return id;
  7. }
  8. public void setId(String id) {
  9. this.id = id;
  10. }
  11. public String getTitle() {
  12. return title;
  13. }
  14. public void setTitle(String title) {
  15. this.title = title;
  16. }
  17. }
  18. I tryied to parse using gson but all I can get is an error: Cannot cast &#39;java.util.LinkedHashMap$LinkedKeyIterator&#39; to &#39;com.google.gson.stream.JsonReader&#39;
  19. So, obviously I&#39;m doing something wrong:
  20. Set&lt;String&gt; availableData = getData(); //this method returns a json string
  21. Iterator&lt;String&gt; itr = availableData.iterator();
  22. while (itr.hasNext()) {
  23. Gson gson = new Gson();
  24. JsonParser parser = new JsonParser();
  25. JsonObject object = (JsonObject) parser.parse(itr.next());
  26. Data data = gson.fromJson(object, Data.class);
  27. }
  28. update: The actual error is: Type mismatch Can&#39;t assign com.google.common.collect.Maps$TransformedEntriesMap to java.lang.String
  29. </details>
  30. # 答案1
  31. **得分**: 1
  32. 在那一行中,你传递了一个迭代器:
  33. ```java
  34. JsonObject object = (JsonObject) parser.parse((JsonReader) itr);

但你应该传递下一个元素:

  1. JsonObject object = (JsonObject) parser.parse(itr.next());

此外,你的 JSON 中多了一个额外的逗号。

你可以用以下代码替换整个块:

  1. Data data = gson.fromJson(itr.next(), Data.class);
英文:

In that line you pass an iterator:

  1. JsonObject object = (JsonObject) parser.parse((JsonReader) itr);

But you should pass a next element:

  1. JsonObject object = (JsonObject) parser.parse(itr.next());

In addition you got an extra comma in you JSON.


You can replace the whole block with that line:

  1. Data data = gson.fromJson(itr.next(),Data.class)

答案2

得分: 0

使用Jackson映射器。您可以直接将其转换为对象,并通过getter方法检索。

  1. ObjectMapper objectMapper = new ObjectMapper();
  2. String carJson =
  3. "{\"brand\": \"Mercedes\", \"doors\": 5}";
  4. try {
  5. Car car = objectMapper.readValue(carJson, Car.class);
  6. System.out.println("car brand = " + car.getBrand());
  7. System.out.println("car doors = " + car.getDoors());
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
英文:

Use Jackson mapper. You can directly convert it into an object and retrieve through getters.

  1. ObjectMapper objectMapper = new ObjectMapper();
  2. String carJson =
  3. &quot;{ \&quot;brand\&quot; : \&quot;Mercedes\&quot;, \&quot;doors\&quot; : 5 }&quot;;
  4. try {
  5. Car car = objectMapper.readValue(carJson, Car.class);
  6. System.out.println(&quot;car brand = &quot; + car.getBrand());
  7. System.out.println(&quot;car doors = &quot; + car.getDoors());
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }

答案3

得分: 0

  1. 所以根据这个相关问题https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5154,最终我使用 Java 8 中的 JSONArray 和流进行了映射。
  2. Set<String> availableData = getData();
  3. JSONArray dataArray = new JSONArray(availableData);
  4. List<Object> dataList = dataArray.toList();
  5. Object o = dataList.stream()
  6. .filter(c -> ((Map) c).get("id").toString().contains("Id1"))
  7. .findFirst().orElse(null);
  8. return ((Map)o).get("id").toString();
英文:

So, following this related issue: https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5154, finally I map this using JSONArray and streams from java8

  1. Set&lt;String&gt; availableData = getData();
  2. JSONArray dataArray = new JSONArray(availableData);
  3. List&lt;Object&gt; dataList = dataArray.toList();
  4. Object o = dataList.stream()
  5. .filter(c -&gt; ((Map) c).get(&quot;id&quot;).toString().contains(&quot;Id1&quot;))
  6. .findFirst().orElse(null);
  7. return ((Map)o).get(&quot;id&quot;).toString();

答案4

得分: 0

  1. public void parse() {
  2. String jsonString = "[
  3. {
  4. \"id\":\"Id1\"
  5. },
  6. {
  7. \"id\":\"Id2\",
  8. \"title\":\"anyTitle\"
  9. }
  10. ]";
  11. Gson gson = new Gson();
  12. // 使用 Gson 的 Type
  13. Type setType = new TypeToken<HashSet<Data>>(){}.getType();
  14. Set<Data> dataSet = gson.fromJson(jsonString, setType);
  15. // 输出 [Data{id='Id2', title='anyTitle'}, Data{id='Id1', title='null'}]
  16. System.out.println(dataSet);
  17. // 使用 Java 数组
  18. Data[] dataArray = gson.fromJson(jsonString, Data[].class);
  19. // 输出 [Data{id='Id1', title='null'}, Data{id='Id2', title='anyTitle'}]
  20. System.out.println(Arrays.toString(dataArray));
  21. }
英文:

Maybe you want to known how to use Gson to unserialized json to java object.

Here are two ways I can give you.

  1. public void parse() {
  2. String jsonString = &quot;[\n&quot; +
  3. &quot; {\n&quot; +
  4. &quot; \&quot;id\&quot;:\&quot;Id1\&quot;\n&quot; +
  5. &quot; },\n&quot; +
  6. &quot; {\n&quot; +
  7. &quot; \&quot;id\&quot;:\&quot;Id2\&quot;,\n&quot; +
  8. &quot; \&quot;title\&quot;:\&quot;anyTitle\&quot;\n&quot; +
  9. &quot; }\n&quot; +
  10. &quot;]&quot;;
  11. Gson gson = new Gson();
  12. // Use Gson Type
  13. Type setType = new TypeToken&lt;HashSet&lt;Data&gt;&gt;(){}.getType();
  14. Set&lt;Data&gt; dataSet = gson.fromJson(jsonString, setType);
  15. // Print [Data{id=&#39;Id2&#39;, title=&#39;anyTitle&#39;}, Data{id=&#39;Id1&#39;, title=&#39;null&#39;}]
  16. System.out.println(dataSet);
  17. // Use Java Array
  18. Data[] dataArray = gson.fromJson(jsonString, Data[].class);
  19. // Print [Data{id=&#39;Id1&#39;, title=&#39;null&#39;}, Data{id=&#39;Id2&#39;, title=&#39;anyTitle&#39;}]
  20. System.out.println(Arrays.toString(dataArray));
  21. }

huangapple
  • 本文由 发表于 2020年4月10日 19:03:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/61138960.html
匿名

发表评论

匿名网友

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

确定