需要帮助反序列化奇怪的Json结构

时间:2013-05-29 16:50:43

标签: java jackson

我正在使用喜欢制作轮子的网络服务。对于一系列对象,它们不是将数据存储在JSON数组中,而是为序列的每个索引创建一个新节点。

{
    "sequence": {
        "0": {
            "foo": "foo",
            "bar": "bar",
            "baz": "baz"
        },
        "1": {
            "foo": "foo",
            "bar": "bar",
            "baz": "baz"
        },
        "2": {
            "foo": "foo",
            "bar": "bar",
            "baz": "baz"
        }
    }
}

我想知道是否有人有一个优雅的解决方案或理智的方法将其反序列化为一个数组或序列bean的集合与杰克逊

public class SequenceElement {
    String foo, bar, baz;
    // Getters and setters below
} 

将序列作为JsonNode处理是我能想出的最好的东西,这里有一些未经测试的sudo代码。

ObjectMapper objectMapper = new ObjectMapper();    

@JsonProperty("sequence")
public void setSequence(JsonNode sequence) {
    List<SequenceElement> list = new ArrayList<SequenceElement>();

    int i = 0;
    while( sequence.get( String.valueOf(i) ) != null ) {
        JsonNode element = sequence.get( String.valueOf(i) );
        list.add( objectMapper.readValue( element, SequenceElement.class );
        i += 1;
    }

    this.sequence = list;
}

2 个答案:

答案 0 :(得分:3)

IMO Map<String,Sequence>应该是JSON对象的Java等价物。

答案 1 :(得分:2)

要扩展@ SubirKumarSao已经正确的答案,这里有一种方法可以将您的序列项目作为列表,按照数据索引保证的顺序:

数据类

public class Sequence {
    private String foo;
    private String bar;
    private String baz;

    // Constructors, getters/setters

    @Override
    public String toString() {
        return String.format("Sequence[foo=%s, bar=%s, baz=%s]", getFoo(),
                getBar(), getBaz());
    }
}

class SequenceHolder {
    private Map<Integer, Sequence> sequence;

    public SequenceHolder() {
        sequence = new TreeMap<Integer, Sequence>();
    }

    // Other constructors, getters/setters
}

主要逻辑

final String json = "JSON HERE";

final SequenceHolder holder = new ObjectMapper().readValue(json,
        SequenceHolder.class);
System.out.println(holder.getSequence().values());

使用此JSON的修改版本进行测试(以说明排序):

{
    "sequence": {
        "0": {
            "foo": "foo0",
            "bar": "bar0",
            "baz": "baz0"
        },
        "1": {
            "foo": "foo1",
            "bar": "bar1",
            "baz": "baz1"
        },
        "2": {
            "foo": "foo2",
            "bar": "bar2",
            "baz": "baz2"
        }
    }
}

<强>输出

  

[Sequence [foo = foo0,bar = bar0,baz = baz0],Sequence [foo = foo1,bar = bar1,baz = baz1],Sequence [foo = foo2,bar = bar2,baz = baz2]] < / p>

如您所见,您将获得一个项目列表,其顺序与数据索引保证的顺序相同(关键是使用树形图)。