将Json反序列化为POJO

时间:2017-03-17 20:59:03

标签: java json jackson jackson2

我正在尝试将以下JSON结构(更大的JSON对象的一部分)转换为POJO,但是获取下面复制的异常(使用Java / Jackson)。

JSON

"outputKeys":
{"ABC":"gGyIioUr4Jfr5QiCm6Z==",
"DEF":"RxHfNyD2JyPOpG5tv3Jaj5g=="}  

Java类

    private class OutputKeys {

        private String key;
        private String value;

        public OutputKeys(String key, String value) {
            this.key = key;
            this.value = value;
        }
}

&安培;

ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonString, Test.class);

异常:

no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?

测试类将OutputKeys作为属性 欢迎大家提出意见。我也尝试过使用List of OutputKeys。

更新

我尝试了以下但没有成功:

class OutputKeys {
public Map<String, String> keys;
///with constructor/setter/getters
}

&安培;

class OutputKeys {
public List<OutputKey> keys;
///with constructor/setter/getters

   public class OutputKey {

        Map<String, String> outputs = new HashMap<>();
// tried this too:
// String key
//String value

}

3 个答案:

答案 0 :(得分:0)

您只需要下面提到的单个类,包含

  1. 所有键(ABC和DEF)
  2. getter / setter方法
  3. toString(),您将使用它与JSON进行交互。

    公共类OutputKeys {     私人字符串ABC;

    private String DEF;
    
    public String getABC ()
    {
        return ABC;
    }
    
    public void setABC (String ABC)
    {
        this.ABC = ABC;
    }
    
    public String getDEF ()
    {
        return DEF;
    }
    
    public void setDEF (String DEF)
    {
        this.DEF = DEF;
    }
    
    @Override
    public String toString()
    {
        return "ClassPojo [ABC = "+ABC+", DEF = "+DEF+"]";
    }
    

    }

  4. 如果您需要更多详细信息,请与我们联系。

答案 1 :(得分:0)

由于密钥是动态的,我最终使用JsonNode上的迭代器反序列化数据:

jsonNode.get("outputKeys").iterator() 

&安培;然后通过迭代器获取相关的动态密钥信息。

答案 2 :(得分:-1)

我需要一个类似NodeJS的工具。这样我就可以对序列化的大型模型(JSON)的部分进行测试。

所以,如果我只需要&#34; ABC&#34;:&#34; gGyIioUr4Jfr5QiCm6Z ==&#34;或&#34; XYZ&#34;:{&#34;你好&#34;:&#34;我的字符串&#34;,&#34;内容&#34;:[1,2,3]},唯一我现在关心测试的属性是:

var sutXYX = { Hello: "My String", Content: [ 1, 2, 2]};

我将此工具编写为实用程序https://github.com/whindes/PojoScriptifyFromJSON