需要将json响应转换为java pojo,其中响应可能返回{}或[{},{}]

时间:2015-01-17 05:39:45

标签: jackson gson json-deserialization to-json jsonresponse

需要将json响应转换为java pojo,其中一个字段(在示例中'表演者'中)可以返回为{}或[{},{}]或null,如下例所示:

例1:performer value here is a list of datas '{}'.

{

    title:"Sample title1",
    performers: {
         performer:[{
              creator: "AAAA",
              linker: "XXX",

         },
         {
              creator: "BBBBB",
              linker: "YYY",

         }]
     },

      venue_address: "sample addr1"

}

示例2:performer value here is just data '{}'


{


    title:"sample title2",
    performers: {
         performer: {
              creator: "AAAA",
              linker: "YYY",
         }
    },
    venue_address: "sample addr2"
}

示例3:performer value is null here

{

    title:"sample title3",
    performers:null,
    venue_address: "sample addr3"
}

如何在gson.fromJson的帮助下将此json响应转换为java pojo。在尝试将其转换为pojo时,将执行者字段作为执行字段列表获取错误"Expecting an OBJECT but found is ARRAY"

1 个答案:

答案 0 :(得分:0)

正确的方法是,

Whether or not you have performers or not it should be an array.
JsonArray should be enclosed with []. even you have ZERO or ONE or More perfomer

示例2:此处的执行者值只是数据“{}”

{
    title:"sample title2",
    performers: [{
        performer: {
          creator: "AAAA",
          linker: "YYY",
        }]
    },
    venue_address: "sample addr2"
}

示例3:此处的执行者值为空

{
    title:"sample title3",
    performers:[],
    venue_address: "sample addr3"
}