如何使用Faster xml迭代具有相同键但具有不同值的Json数组 [英] How to iterate through an Json array with same keys, but different values using Faster xml

查看:254
本文介绍了如何使用Faster xml迭代具有相同键但具有不同值的Json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我正在尝试使用相同的键值来解析json数组,该键值类似于:
  1. I am trying to parse the json array with same key value which looks something like:

Back End Response:"Countries":[{"state":"Queens Land "state":"Tasmania"}].

2.我创建了一些类来读取后端响应并使用faster XML映射值,但是仅复制数组中的最后一个值,而不是整个数组.这就是我创建Data Transfer Object类的方式.

2.I have created classes to read back end response and mapping the values with faster XML, but only the last value in the array is getting copied, instead of entire array. This is how I created my Data Transfer Object classes.

现在Test对象包含Countries数组,但是仅读取State值之一.即

Now the Test object contains Countries array, but only one of the State value is read. i.e

"Countries":["States":"Tasmania"].

请原谅我输入错误.可以帮一个忙,可以建议一下波纹管代码怎么了..

Please excuse me for typos. can some one help, can some one suggest whats wrong with the bellow code..

private Class Test{
  List<Countries> countries;
}

private class Countries{        
  private String States;
}

private class Mapper {

}

在我的Mapper类中,使用更快的XML读取值

In my Mapper class reading the value using faster XML

推荐答案

假设您的JSON有效载荷是:

{
  "Countries": [
    {
      "state": "Queens Land",
      "state": "Tasmania"
    }
  ]
}

根据 RFC7159 :

对象结构表示为一对大括号 周围零个或多个名称/值对(或成员).名字是一个 细绳.每个名称后都有一个冒号,将名称分开 从价值.单个逗号将值与后跟 姓名. 对象中的名称应唯一.

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

在您的示例中,您没有唯一的名称,大多数JSON解析器将跳过重复的值,并且仅使用一个.因此,如果您可以更改后端响应,只需将其更改为:

In your example, you have not unique names and most JSON parsers would skip repeated values and would take only one. So, if you can change backend response, just change it to:

{
  "Countries": [
    {
      "state": "Queens Land"
    },
    {
      "state": "Tasmania"
    }
  ]
}

{
  "Countries": [
    "Queens Land",
    "Tasmania"
  ]
}

但是,如果不能这样做,则需要使用 Streaming API 和实现您的自定义解串器.参见以下示例:

But if you can not do that, you need to use Streaming API and implement your custom deserialiser. See below example:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        Test test = mapper.readValue(jsonFile, Test.class);
        System.out.println(test);
    }
}

class CountriesJsonDeserializer extends JsonDeserializer<Countries> {

    @Override
    public Countries deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        List<String> states = new ArrayList<>();
        while (p.nextToken() != JsonToken.END_OBJECT) {
            if (p.currentToken() == JsonToken.FIELD_NAME) {
                if ("state".equalsIgnoreCase(p.getText())) {
                    p.nextToken();
                    states.add(p.getText());
                }
            }
        }

        Countries countries = new Countries();
        countries.setStates(states);
        return countries;
    }
}

class Test {

    @JsonProperty("Countries")
    private List<Countries> countries;

    public List<Countries> getCountries() {
        return countries;
    }

    public void setCountries(List<Countries> countries) {
        this.countries = countries;
    }

    @Override
    public String toString() {
        return "Test{" +
                "countries=" + countries +
                '}';
    }
}

@JsonDeserialize(using = CountriesJsonDeserializer.class)
class Countries {
    private List<String> states;

    public List<String> getStates() {
        return states;
    }

    public void setStates(List<String> states) {
        this.states = states;
    }

    @Override
    public String toString() {
        return "Countries{" +
                "states=" + states +
                '}';
    }
}

上面的示例打印:

Test{countries=[Countries{states=[Queens Land, Tasmania]}]}

另请参阅:

这篇关于如何使用Faster xml迭代具有相同键但具有不同值的Json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆