繁体   English   中英

将Json解析为包含对象的对象

[英]Parse Json to object containing objects

我有以下代码与json,我从accuweather得到

{  
 "Headline":{  
      "EffectiveDate":"2019-07-29T07:00:00+06:00",
      "EffectiveEpochDate":1564362000,
      "Severity":3,
      "Text":"The heat wave will continue through Friday",
      "Category":"heat",
      "EndDate":"2019-08-02T19:00:00+06:00",
      "EndEpochDate":1564750800
   },
   "DailyForecasts":[  
      {  
         "Date":"2019-07-29T07:00:00+06:00",
         "EpochDate":1564362000,
         "Temperature":{  
            "Minimum":{  
               "Value":19.1,
               "Unit":"C",
               "UnitType":17
            },
            "Maximum":{  
               "Value":36.7,
               "Unit":"C",
               "UnitType":17
            }
         },
         "Day":{  
            "Icon":30,
            "IconPhrase":"Hot",
            "HasPrecipitation":false
         },
         "Night":{  
            "Icon":35,
            "IconPhrase":"Partly cloudy",
            "HasPrecipitation":false
         },
         "Sources":[  
            "AccuWeather"
         ]
      }
   ]
}

我尝试通过jackson将这个对象解析为POJO

public static void main( String[] args )
{
    String x = "{\"Headline\":{\"EffectiveDate\":\"2019-07-29T07:00:00+06:00\",\"EffectiveEpochDate\":1564362000,\"Severity\":3,\"Text\":\"The heat wave will continue through Friday\",\"Category\":\"heat\",\"EndDate\":\"2019-08-02T19:00:00+06:00\",\"EndEpochDate\":1564750800},\"DailyForecasts\":[{\"Date\":\"2019-07-29T07:00:00+06:00\",\"EpochDate\":1564362000,\"Temperature\":{\"Minimum\":{\"Value\":19.1,\"Unit\":\"C\",\"UnitType\":17},\"Maximum\":{\"Value\":36.7,\"Unit\":\"C\",\"UnitType\":17}},\"Day\":{\"Icon\":30,\"IconPhrase\":\"Hot\",\"HasPrecipitation\":false},\"Night\":{\"Icon\":35,\"IconPhrase\":\"Partly cloudy\",\"HasPrecipitation\":false},\"Sources\":[\"AccuWeather\"]}]}";
    ObjectMapper objectMapper = new ObjectMapper();

    try {
        Weather weather = objectMapper.readValue(x, Weather.class);

        System.out.println(weather);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我有json中指定的所有模型,如HeadlineDailyForecasts数组, Temperature包含TemperatureItems (在json中命名为minimum和maximum)等等,所有模型都有私有字段和公共构造函数,getter和setter。 但是我没有一些字段,因为我想省略它们(Day,Night,EpochDate,Source)。

当我运行程序时,我收到错误

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造test.models.weather.Weather实例(没有test.models.weather.Weather ,如默认构造,存在):无法从Object值反序列化(没有基于委托或属性的Creator)

我也尝试过Gson但它返回Null值的对象

难道我做错了什么? 还有另一种方法吗?

编辑 :这些是模型,@ LazerBass是对的,因为我首先没有包含默认构造函数,现在错误已经改变:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段“标题”(类test.models.weather.Weather),未标记为可忽略(2个已知属性:“标题”,“dailyForecasts”])

public class TemperatureItem {
    public double value;
    public String unit;
    public String unitType;

    public TemperatureItem() {

    }

    //Getters and setters
}


public class Temperature {
    private TemperatureItem maximum;
    private TemperatureItem minimum;

    public Temperature(TemperatureItem maximum, TemperatureItem minimum) {
        this.maximum = maximum;
        this.minimum = minimum;
    }

    public Temperature() {

    }
    //Getters and setters
}

public class DailyForecasts {
    private LocalDateTime date;
    private Temperature temperature;

    public DailyForecasts(LocalDateTime date, Temperature temperature) {
        this.date = date;
        this.temperature = temperature;
    }

    public DailyForecasts() {

    }
    //Getters and setters
}

public class Headline {
    private LocalDateTime effectiveDate;
    private int severity;
    private String text;
    private String category;
    private LocalDateTime endDate;

    public Headline() {

    }

    public Headline(LocalDateTime effectiveDate, Integer severity, String text, String category, LocalDateTime endDate) {
        this.effectiveDate = effectiveDate;
        this.severity = severity;
        this.text = text;
        this.category = category;
        this.endDate = endDate;
    }
    //Getters and setters
}

public class Weather {
        private Headline headline;
        private DailyForecasts[] dailyForecasts;

        public Weather() {

        }
        public Weather(Headline headline, DailyForecasts[] dailyForecasts) {
            this.headline = headline;
            this.dailyForecasts = dailyForecasts;
        }
        //Getters and setters
}

我发现,如果我将json字符串转换为小写,我可以得到一些值,虽然没有解析ArrayLocalDateTime

从异常消息判断我猜你的Weather类正在使用无参数构造函数。 尝试添加一个。 例如

public class Weather {
    public Weather() {
        // no arg constructor needed for jackson
    }
}

要生成Weather类及其对应的类,请使用以下链接并选择源类型为json。 它将根据json字符串生成所需的类。

http://www.jsonschema2pojo.org/

生成类后,可以使用@JsonIgnore注释不需要的字段。

Jackson失败时会出现“ 没有创建者,就像默认构造,存在 ”这样的消息它需要你模型中每个POJO类的默认的public no-argument构造函数。

当它失败并显示“ 无法识别的字段...未标记为可忽略的... ”之类的消息时,您需要禁用FAIL_ON_UNKNOWN_PROPERTIES功能。

也可以看看:

  1. Jackson Unmarshalling JSON具有未知属性
  2. 杰克逊推迟反序列化领域

暂无
暂无

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

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