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

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

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&#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"
}
]


My goal is to get the value of key &quot;id&quot;. I&#39;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 &#39;java.util.LinkedHashMap$LinkedKeyIterator&#39; to &#39;com.google.gson.stream.JsonReader&#39;

So, obviously I&#39;m doing something wrong:

    Set&lt;String&gt; availableData = getData(); //this method returns a json string
    Iterator&lt;String&gt; 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&#39;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 =
    &quot;{ \&quot;brand\&quot; : \&quot;Mercedes\&quot;, \&quot;doors\&quot; : 5 }&quot;;

try {
    Car car = objectMapper.readValue(carJson, Car.class);

    System.out.println(&quot;car brand = &quot; + car.getBrand());
    System.out.println(&quot;car doors = &quot; + 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&lt;String&gt; availableData = getData();
        JSONArray dataArray = new JSONArray(availableData);
        List&lt;Object&gt; dataList = dataArray.toList();
        Object o = dataList.stream()
                .filter(c -&gt; ((Map) c).get(&quot;id&quot;).toString().contains(&quot;Id1&quot;))
                .findFirst().orElse(null);
        return ((Map)o).get(&quot;id&quot;).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 = &quot;[\n&quot; +
            &quot;  {\n&quot; +
            &quot;   \&quot;id\&quot;:\&quot;Id1\&quot;\n&quot; +
            &quot;  },\n&quot; +
            &quot;  {\n&quot; +
            &quot;  \&quot;id\&quot;:\&quot;Id2\&quot;,\n&quot; +
            &quot;  \&quot;title\&quot;:\&quot;anyTitle\&quot;\n&quot; +
            &quot;  }\n&quot; +
            &quot;]&quot;;

        Gson gson = new Gson();
        
        // Use Gson Type
        Type setType = new TypeToken&lt;HashSet&lt;Data&gt;&gt;(){}.getType();
        Set&lt;Data&gt; dataSet = gson.fromJson(jsonString, setType);
        
        // Print [Data{id=&#39;Id2&#39;, title=&#39;anyTitle&#39;}, Data{id=&#39;Id1&#39;, title=&#39;null&#39;}]
        System.out.println(dataSet);

        // Use Java Array
        Data[] dataArray = gson.fromJson(jsonString, Data[].class);
        
        // Print [Data{id=&#39;Id1&#39;, title=&#39;null&#39;}, Data{id=&#39;Id2&#39;, title=&#39;anyTitle&#39;}]
        System.out.println(Arrays.toString(dataArray));

    }

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:

确定