简体   繁体   English

使用JSON编组字符串

[英]Marshalling Strings by using JSON

I am using JSON Jackson 2.0 to write a data Model to file and then load it back into the application. 我正在使用JSON Jackson 2.0将数据模型写入文件,然后将其加载回应用程序中。 I can successfully write the object into a string but I encounter the following error message when trying to marshal it back into a object: 我可以成功地将对象写入字符串,但是在尝试将其编组回对象时遇到以下错误消息:

No suitable constructor found for type [simple type, class ImportAttributeModel]: can not instantiate from JSON object (need to add/enable type information?) at [Source: user; 在类型[简单类型,类ImportAttributeModel]中找不到合适的构造函数:无法在[来源:用户;无法从JSON对象实例化(需要添加/启用类型信息?)。 line: 1, column: 111] (through reference chain: ImportTemplateModel["modelList"]) 行:1,列:111](通过参考链:ImportTemplateModel [“ modelList”])

This is a code snippet of my classes: 这是我的课程的代码片段:

public class ImportTemplateModel 
{  
  private Map<Integer, AttributeModel> m_modelList;
  private GraphElementType m_type; 

  public ImportTemplateModel() 
  {

  }
// getters  & setters
}

public class AttributeModel 
{
   private String m_label;
   private String m_key;
   private ElementDefinition m_definition;

   public AttributeModel(String label, String key, ElementDefinition def)
   {
      m_label = label;
      m_key = key;
      m_definition = def;
   }
// getters  & setters
}

Here is the calls I make to write & read the model: 这是我为编写和读取模型而进行的调用:

// Write model
ObjectMapper mapper = new ObjectMapper();
ImportTemplateModel itm = new ImportTemplateModel()
// set model atttributes
...
//

try {
  mapper.writeValue(new File(filepath), itm);

} 
catch (IOException e) {

}
.... 

// Read Model
ObjectMapper mapper = new ObjectMapper();
try {
  mapper.readValue(new File(filepath), ImportTemplateModel.class);

}
catch (IOException e) {

}

I am not sure what I am doing wrong at the moment... Is it because AttributeModel is not a POJO? 我现在不确定我在做什么错...是因为AttributeModel不是POJO吗? or is it I can't use Maps for this implementation? 还是我无法将Maps用于此实现? If so, how do I get around this? 如果是这样,我该如何解决?

它需要有一个无参数的构造函数,以便Jackson可以实例化它。

Exception: 例外:

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class ImportDataModel$ImportTemplateModel]: can not instantiate from JSON object (need to add/enable type information?) com.fasterxml.jackson.databind.JsonMappingException:没有为类型[简单类型,类ImportDataModel $ ImportTemplateModel]找到合适的构造函数:无法从JSON对象实例化(需要添加/启用类型信息吗?)

suggests that ImportTemplateModel is an inner class. 建议ImportTemplateModel是一个内部类。 Your code snippet shows that this class is not static. 您的代码段显示该类不是静态的。 If it is not static, it cannot be instantiated outside of its outer class ImportDataModel . 如果它不是静态的,则不能在其外部类ImportDataModel之外实例化它。 Make it static or standalone class and it should work. 使它成为静态或独立类,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM