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

时间:2019-07-29 16:30:58

标签: java json jackson

我有以下来自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"
         ]
      }
   ]
}

我尝试通过杰克逊将该对象解析为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中指定的所有模型,例如HeadlineDailyForecastsTemperature的数组,其中包括TemperatureItems(在json中命名为最小值和最大值),等等,它们都有私有字段和公共构造函数,getter和setter。但是我没有某些字段,因为我想忽略它们(Day,Night,EpochDate,Source)。

运行程序时出现错误

  

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造test.models.weather.Weather的实例(不存在创建者,如默认构造一样):无法从对象值反序列化(不存在基于委托或基于属性的创建者)

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

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

编辑:这些是模型,@ LazerBass是正确的,因为我首先不包括默认构造函数,现在错误已更改:

  

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

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
}

我发现,即使不解析ArrayLocalDateTime,如果将json字符串转换为小写,我也可以获得一些值

3 个答案:

答案 0 :(得分:1)

从异常消息来看,我猜想您的Weather类正在构造一个无参数的构造函数。尝试添加一个。例如

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

答案 1 :(得分:1)

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

http://www.jsonschema2pojo.org/

生成类之后,可以使用@JsonIgnore注释字段,这不是必需的。

答案 2 :(得分:1)

Jackson失败并显示诸如“ 没有创建者,例如默认构造”之类的消息时,它需要使用默认的public no-argument构造函数,每个{{1 }}您模型中的类。

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

另请参阅:

  1. Jackson Unmarshalling JSON with Unknown Properties
  2. jackson delay deserializing field
相关问题