【问题标题】:Jackson - JsonMappingException due to constructorJackson - 由于构造函数导致的 JsonMappingException
【发布时间】:2012-10-11 09:01:23
【问题描述】:

尝试反序列化 JSON 时遇到以下异常

找不到适合类型[simple type, class MyObj$obj$Card]: 的构造函数,无法从[Source: java.io.StringReader@4344ee21; line: 1, column: 201] 处的JSON 对象实例化(需要添加/启用类型信息?)(通过引用链:MyObj["obj"]->Obj["cards"])

JSON 是

{
  "obj":{
  "api":"OK",
  "cache":false,
  "cards":[
     {
        "id":1232995897,
        "items":[
           {
              "id":"vmdSJLpnY",
              "cat":50,
              "rating":0.0
           }
        ]
     },
     {
        "id":0005897,
        "items":[
           {
              "id":"vxdSJLpnY",
              "cat":50,
              "rating":0.0
           }
        ]
     }
 ]
 }
}

在Obj 类中,我有以下声明

@JsonProperty("cards") private Card[] cards;

这会产生上述异常。将类型 Card[] 更改为 Object[] 不会产生异常,但它缺少我想要获得的正确映射。

任何线索我该如何解决它? sn-p 会很棒! 这个错误到底意味着什么?

更新

我已经包含了 Java 类。

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.Gson;

@JsonIgnoreProperties(ignoreUnknown=true)
public final class MyObj {
    @JsonIgnoreProperties(ignoreUnknown=true)
    public final class Obj {
        @JsonIgnoreProperties(ignoreUnknown=true)
        public final class Card {
            @JsonIgnoreProperties(ignoreUnknown=true)
            public final class Item {
                @JsonProperty("id") private String id;
                @JsonProperty("cat") private String cat;
                @JsonProperty("rating") private String rating;
                public final String getId() { return id; }
                public final String getCat() { return cat; }
                public final String getRating() { return ranting; }
                public final String toString() { return new Gson().toJson(this); }
            }

            @JsonProperty("items") private Item[] items;
            public final Item[] getItems() { return items; }
            public final String toString() { return new Gson().toJson(this); }
        }

        @JsonProperty("cards") private Card[] cards;
        public Card[] getCards() { return cards; }
        public final String toString() { return new Gson().toJson(this); }      
    }


    @JsonProperty("obj") MyObj obj;
    public final Card[] getCards(){ return apiServiceResultsNoLists.getCards(); }
}

【问题讨论】:

  • 请显示将用于对象映射器的java类。
  • 如果使用上面的确切结构,错误是由于jackson无法反序列化为内部类。如果您将它们定义为静态,则问题应该得到解决
  • 嗨,Eugen,您的评论有资格作为答案,但不能被接受和赞成
  • @eugen,我已将Obj、Card 类更改为静态,但我仍然收到相同的错误。无论如何,我能够实例化不包括数组的内部类。 是数组导致了所有问题
  • 用您所拥有的内容更新您的代码,这将有助于我们解决问题。所有内部类都必须是静态的。

标签: java json jackson gson


【解决方案1】:

我认为问题很可能出在 Card 对象上

  • 它可能没有默认构造函数
  • 如果它没有默认构造函数,则应使用 @JsonCreator 进行注释

编辑 我有两件事:
* 你没有二传手。
*您没有可以设置您的文件的公共构造函数。

如果你不给它任何(合法*)手段,反序列化器应该如何填充你的字段?

解决方案:
-> 将公共设置器添加到类
-> 或创建带有 @JsonCreator 注释的参数化构造函数

*:当然,解析器可以做反射性的“修改可见性”技巧,但是拜托,这不是“它的播放方式”

EDIT2 我认为这应该可行,但我无法对其进行测试——我手头没有一个项目,杰克逊现在正确设置(这只是其中的一部分,但我认为很容易解释我想要的显示。)注意,我将数组更改为列表:

    @JsonIgnoreProperties(ignoreUnknown=true)     
public final class Card {     
    @JsonIgnoreProperties(ignoreUnknown=true)

    public final class Item {     
        @JsonProperty("id") private String id;     
        @JsonProperty("cat") private String cat;     
        @JsonProperty("rating") private String rating;     

        @JsonCreator
        public Item(@JsonProperty("id") String id, @JsonProperty("cat") String cat, @JsonProperty("rating") String rating) {
            this.id = id;
            this.cat = cat;
            this.rating = rating;
        }   


        public final String getId() { return id; }     
        public final String getCat() { return cat; }     
        public final String getRating() { return ranting; }     
        public final String toString() { return new Gson().toJson(this); }     
    }     
    @JsonProperty("items") private List<Item> items;     

    @JsonCreator
    public Card(@JsonProperty("items") List<Item> items) {
        this.items = items;
    }       

    public final List<Item> getItems() { return items; }     

    public final String toString() { return new Gson().toJson(this); }     
}     

【讨论】:

  • 查看我对 Konstantin Pribluda 的回答
  • 这并不完全正确。 (我的意思是 def. 构造函数总是存在的......)如果您指定了另一个构造函数,则不是,它有一个参数。在这种情况下,默认构造函数不存在。 (注意:我在您编辑问题以显示代码之前添加了我的答案...)
  • 我正在使用`@JsonIgnoreProperties(ignoreUnknown=true)`,所以当没有使用@JsonProperty的显式映射时,它将被忽略。当使用JsonProperty 进行映射时,访问器(getters\setters)不需要使用这个注解。
  • 我似乎无法正确生成您的解决方案。你能附上一个小sn-p吗?
  • @MrRoth(回复上一条之前的评论)我明白了。但是 JSON 解析器不处于“上帝模式”,因此它无法填充您的字段:1,它们是私有的。 2,他们没有公开的二传手。 3,没有允许在对象创建时设置它们的构造函数。 解析器应该如何设置它们的值?
【解决方案2】:

前几天我也有同样的症状,并接受了关于 JsonCreator 和 JsonProperty 的建议,但我得到了同样的错误信息。事实证明,我正在从事的项目使用的是 fastxml 和 codehaus 的 jackson 版本。我将 codehaus 属性放在我的类上,但使用 fasterxml 的 ObjectMapper 进行解析。他们喜欢传递依赖。

【讨论】:

  • 对此表示赞同。阅读所有文档,但杰克逊仍然期待一个默认构造函数。疯狂阅读 jsonproperty 和 jsoncreator 的文档,直到我意识到 objectmapper 类是 codehaus 版本。并且注释是fastxml 版本。我把所有东西都做成了 fastxml 版本,它工作正常。
【解决方案3】:

我也遇到过同样的问题。我的 Json 数据集如下

{ “计数”:1917, “数据”: [ { “id”:“1”, "generated_id": "Z1-1156", "first_name": "Maruf", "last_name": "艾哈迈德", "full_name": "Maruf Ahmed 先生", “电子邮件”:“maruf1990@gmail.com”, "电话": "+8801676798306", "company_name": "SM Style Ltd.", "网站": "http:\\/\\/smartex-bd.com\\/", "地址": "\\\n路号:5 楼号:18\\\n等级:3\\\n车道:\\\n街区:F\\\n扇区:2\\\n地区:米尔普尔\\\n达卡1216 \\\nMirpur\\\n孟加拉国", "industry_type": "服装零售商", "job_title": "设计师", “部门”:“研发”, “日期”:“7\\/10\\/2015 下午 1:04:43” }, { “id”:“2”, "generated_id": "Z2-1157", "first_name": "Akramul", "last_name": "Hoque", "full_name": "Akramul Hoque 先生", “电子邮件”:“akram@nassagroup.org”, "电话": "+8801732005564", "company_name": "纳萨集团", "网站": "www,nassagroup.org", "地址": "纳萨集团\\\n路号:238门牌号:\\\n层级:\\\n车道:\\\n地块:\\\n扇区:\\\n地区:高尔山里\\\n达卡1208\ \\nTejgaon 工业区\\\n孟加拉国", "industry_type": "牛仔服装制造商", "job_title": "跟单员(高级)", “部门”:“销售”, “日期”:“7\\/9\\/2015 晚上 10:56:22” } ] }
        @JsonIgnoreProperties(ignoreUnknown = true)
    public class Visitors {



      @JsonIgnoreProperties(ignoreUnknown = true)
      public static class Visitor{
        @JsonProperty("id")
        public String mId;

        @JsonProperty("generated_id")
        public String mGenId;

        @JsonProperty("first_name")
        public String mFirstName;

        @JsonProperty("last_name")
        public String mLastName;

        @JsonProperty("full_name")
        public String mFullName;

        @JsonProperty("email")
        public String mEmail;

        @JsonProperty("phone")
        public String mPhone;

        @JsonProperty("company_name")
        public String mCompanyName;

        @JsonProperty("website")
        public String mWebsite;

        @JsonProperty("address")
        public String mAdress;

        @JsonProperty("industry_type")
        public String mIndustryType;

        @JsonProperty("job_title")
        public String mJobtitle;

        @JsonProperty("department")
        public String mDepartment;

        @JsonProperty("date")
        public String mDate;


        public Visitor(@JsonProperty("id") String  Id,
                       @JsonProperty("generated_id") String  GenId,
                       @JsonProperty("first_name") String  FirstName,
                       @JsonProperty("last_name") String  LastName,
                       @JsonProperty("full_name") String  FullName,
                       @JsonProperty("email") String  Email,
                       @JsonProperty("phone") String  Phone,
                       @JsonProperty("company_name") String  CompanyName,
                       @JsonProperty("website") String  Website,
                       @JsonProperty("address") String  Adress,
                       @JsonProperty("industry_type") String  IndustryType,
                       @JsonProperty("job_title") String  Jobtitle,
                       @JsonProperty("department") String  Department,
                       @JsonProperty("date") String  date)
        {
          mId = Id;
          mGenId = GenId;
          mFirstName = FirstName;
          mLastName= LastName;
          mFullName= FullName;
          mEmail= Email;
          mPhone= Phone;
          mCompanyName= CompanyName;
          mWebsite= Website;
          mAdress= Adress;
          mIndustryType= IndustryType;
          mJobtitle= Jobtitle;
          mDepartment= Department;
          mDate= date;
        }
      }


      @JsonProperty("count") public String mCount;


      @JsonProperty("data")  public ArrayList<Visitor> mVisitorList;

      @JsonCreator
      public Visitors(  @JsonProperty("count") String Count,
                        @JsonProperty("data") ArrayList<Visitor> visitorList)
      {
        mCount = Count;
        mVisitorList = visitorList;
      }
    }

问题是内部类声明,它应该是静态的。因为杰克逊需要像这样访问它

new Visitors.Visitor();

所以我将内部Visitor 类声明为static。它对我有用。

【讨论】:

  • 需要静态的内部类解决了我的问题。不需要@JsonCreator。
  • 谢谢。使我的内部班级静态也对我有用。但我需要知道,如果我们创建一个新类并获得 has-a 关系,那它会起作用吗?
  • 你将如何指定有关系,你会分享一些代码来创建有关系吗? @ShabbirEssaji
【解决方案4】:

我认为您在其中一个类中缺少默认构造函数。
或者:在构造函数中添加 @JsonCreator 注解

【讨论】:

  • 能否提供一个小sn-p?
【解决方案5】:

查看您的 Card 类 - 很可能没有可访问的默认构造函数或构造函数缺少正确的映射。

【讨论】:

  • 默认构造函数默认存在。因此得名。即使明确包含它也不能解决问题。您能否为“正确映射”发布一个小的 sn-p?
  • 它存在但不一定可访问。正如 eugen 所说,您需要将这个内部类设为静态(因为存在具有封闭类类型的隐式构造函数参数)
  • @KonstantinPribluda 没错。实际上,当您对内部类使用自省时,您会看到位置 0 处有一个附加参数,对应于封闭类的实例。
【解决方案6】:

为类和所有嵌套的用户定义类添加默认构造函数。那么它应该可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 2012-09-29
    • 2021-11-30
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2012-01-12
    相关资源
    最近更新 更多