英文:
Java: Get value from a Json string (Set<String>)
问题
我正在使用这个方法,它返回一个`Set<String>`,但实际上我得到的是一个像这样的Json字符串:
[
{
"id":"Id1"
},
{
"id":"Id2",
"title":"anyTitle"
}
]
我的目标是获取键"id"的值。我还创建了一个Java Bean来映射数据:
```java
public class Data {
private String id;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
我尝试使用gson解析,但我得到的只是一个错误:无法将'java.util.LinkedHashMap$LinkedKeyIterator'转换为'com.google.gson.stream.JsonReader'。
所以,显然我做错了什么:
Set<String> availableData = getData(); // 这个方法返回一个json字符串
Iterator<String> itr = availableData.iterator();
while (itr.hasNext()) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(itr.next());
Data data = gson.fromJson(object, Data.class);
}
更新:实际错误是:类型不匹配,无法将'com.google.common.collect.Maps$TransformedEntriesMap'分配给'java.lang.String'。
<details>
<summary>英文:</summary>
I'm using this method that returns a `Set<String>` but in fact what I got is a Json string like this
[
{
"id":"Id1"
},
{
"id":"Id2",
"title":"anyTitle"
}
]
My goal is to get the value of key "id". I've also made a java bean to map the data:
public class Data {
private String id;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I tryied to parse using gson but all I can get is an error: Cannot cast 'java.util.LinkedHashMap$LinkedKeyIterator' to 'com.google.gson.stream.JsonReader'
So, obviously I'm doing something wrong:
Set<String> availableData = getData(); //this method returns a json string
Iterator<String> itr = availableData.iterator();
while (itr.hasNext()) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(itr.next());
Data data = gson.fromJson(object, Data.class);
}
update: The actual error is: Type mismatch Can't assign com.google.common.collect.Maps$TransformedEntriesMap to java.lang.String
</details>
# 答案1
**得分**: 1
在那一行中,你传递了一个迭代器:
```java
JsonObject object = (JsonObject) parser.parse((JsonReader) itr);
但你应该传递下一个元素:
JsonObject object = (JsonObject) parser.parse(itr.next());
此外,你的 JSON 中多了一个额外的逗号。
你可以用以下代码替换整个块:
Data data = gson.fromJson(itr.next(), Data.class);
英文:
In that line you pass an iterator:
JsonObject object = (JsonObject) parser.parse((JsonReader) itr);
But you should pass a next element:
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:
Data data = gson.fromJson(itr.next(),Data.class)
答案2
得分: 0
使用Jackson映射器。您可以直接将其转换为对象,并通过getter方法检索。
ObjectMapper objectMapper = new ObjectMapper();
String carJson =
"{\"brand\": \"Mercedes\", \"doors\": 5}";
try {
Car car = objectMapper.readValue(carJson, Car.class);
System.out.println("car brand = " + car.getBrand());
System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
e.printStackTrace();
}
英文:
Use Jackson mapper. You can directly convert it into an object and retrieve through getters.
ObjectMapper objectMapper = new ObjectMapper();
String carJson =
"{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
try {
Car car = objectMapper.readValue(carJson, Car.class);
System.out.println("car brand = " + car.getBrand());
System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
e.printStackTrace();
}
答案3
得分: 0
所以,根据这个相关问题:https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5154,最终我使用 Java 8 中的 JSONArray 和流进行了映射。
Set<String> availableData = getData();
JSONArray dataArray = new JSONArray(availableData);
List<Object> dataList = dataArray.toList();
Object o = dataList.stream()
.filter(c -> ((Map) c).get("id").toString().contains("Id1"))
.findFirst().orElse(null);
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
Set<String> availableData = getData();
JSONArray dataArray = new JSONArray(availableData);
List<Object> dataList = dataArray.toList();
Object o = dataList.stream()
.filter(c -> ((Map) c).get("id").toString().contains("Id1"))
.findFirst().orElse(null);
return ((Map)o).get("id").toString();
答案4
得分: 0
public void parse() {
String jsonString = "[
{
\"id\":\"Id1\"
},
{
\"id\":\"Id2\",
\"title\":\"anyTitle\"
}
]";
Gson gson = new Gson();
// 使用 Gson 的 Type
Type setType = new TypeToken<HashSet<Data>>(){}.getType();
Set<Data> dataSet = gson.fromJson(jsonString, setType);
// 输出 [Data{id='Id2', title='anyTitle'}, Data{id='Id1', title='null'}]
System.out.println(dataSet);
// 使用 Java 数组
Data[] dataArray = gson.fromJson(jsonString, Data[].class);
// 输出 [Data{id='Id1', title='null'}, Data{id='Id2', title='anyTitle'}]
System.out.println(Arrays.toString(dataArray));
}
英文:
Maybe you want to known how to use Gson to unserialized json to java object.
Here are two ways I can give you.
public void parse() {
String jsonString = "[\n" +
" {\n" +
" \"id\":\"Id1\"\n" +
" },\n" +
" {\n" +
" \"id\":\"Id2\",\n" +
" \"title\":\"anyTitle\"\n" +
" }\n" +
"]";
Gson gson = new Gson();
// Use Gson Type
Type setType = new TypeToken<HashSet<Data>>(){}.getType();
Set<Data> dataSet = gson.fromJson(jsonString, setType);
// Print [Data{id='Id2', title='anyTitle'}, Data{id='Id1', title='null'}]
System.out.println(dataSet);
// Use Java Array
Data[] dataArray = gson.fromJson(jsonString, Data[].class);
// Print [Data{id='Id1', title='null'}, Data{id='Id2', title='anyTitle'}]
System.out.println(Arrays.toString(dataArray));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论