为Json Array创建映射类 [英] Creating mapping class for Json Array

查看:54
本文介绍了为Json Array创建映射类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Json文件下面给出

Given below the Json file

[
  "a",
  "b",
  "c"
]

我需要为上述Json创建POJO类。我在下面的代码中尝试过

I need to create POJO class for above Json. I tried below code

public class Elements{
  public String element;
  public Elements(String element){
    this.element = element;
  }
}

.........

.........

public class OuterElement{
   Elements[] elements;
   //Getter and Setter
}

但是我得到了例外 p>

But I get below exception

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of [...] out of START_ARRAY token

在这种情况下,POJO类应该如何?

How should be the POJO class in this case?

推荐答案

您需要创建带有 List< String> 参数的构造函数,并使用 @JsonCreator 。下面是一个简单的示例:

You need to create constructor which takes List<String> parameter and annotate it with @JsonCreator. Simple example below:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import java.util.List;

public class Test {

    public static void main(String[] args) throws Exception {
        String json = "[\"a\",\"b\",\"c\"]";

        ObjectMapper mapper = new ObjectMapper();
        OuterElement outerElement = mapper.readValue(json, OuterElement.class);

        System.out.println(outerElement);
    }
}

class Element {

    private String value;

    public Element(String value) {
        this.value = value;
    }

    // getters, setters, toString
}

class OuterElement {

    private Element[] elements;

    @JsonCreator
    public OuterElement(List<String> elements) {
        this.elements = new Element[elements.size()];
        int index = 0;
        for (String element : elements) {
            this.elements[index++] = new Element(element);
        }
    }

    // getters, setters, toString
}

以上代码输出:

OuterElement{elements=[Element{value='a'}, Element{value='b'}, Element{value='c'}]}

这篇关于为Json Array创建映射类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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