如何将嵌套的JSON映射到简单对象?

时间:2018-01-15 13:10:57

标签: java json serialization mapping deserialization

我想映射这个JSON数据:

{"information":{
     "type": "typeA",
     "date": "2018-01-15 12:11:53",
     "user":{
         "name": "John"
         "lastName": "Doe"
     }
}}

到这个java对象:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InformationModel {
    private String name;
    private String lastName;

    private String type;
    private String date;
}

但它失败了,所有的值都是null。我尝试在@JsonProperty("information.type")变量上方添加type,但没有成功。

是否可以反序列化JSON以便它只映射到(这个)一个类?

编辑:我使用Spring StreamListener进行这样的映射:

@StreamListener(value = Sink.INPUT)
public void on(InformationModel message) throws IOException {
    // some code using message
}

4 个答案:

答案 0 :(得分:1)

我必须承认我对Spring不太了解,所以我的回答可能不合适,但由于你用java标记了你的问题,这是我的答案(使用org.json):

String jsonString = "{\"information\":{\"type\": \"typeA\",\"date\": \"2018-01-15 12:11:53\",\"user\":{\"name\": \"John\",\"lastName\": \"Doe\"}}}";

JSONObject o = new JSONObject(jsonString);

JSONObject obj = o.getJSONObject("information");
String date = obj.getString("date");
//map whatever you want to map here.    
System.out.println(date);

显然它非常基本,但你明白了。您可以使用JSONArray实现相同的目标。

希望它有所帮助!

答案 1 :(得分:1)

我们有几种方法可以解决这个问题。 As explained here.。我尝试过使用带注释的Mapping,但它对我没用。有效的是JsonNode,如下所述。

1 InformationModel.java

`@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InformationModel {
private String type;
private String date;
private String lastName;
private String name;
//getters and setters
}
`

[2] TestDemo.java

    public class TestDemo { 
    public static void main(String args[]) throws JsonParseException,
            JsonMappingException, IOException { 
        ObjectMapper mapper = new ObjectMapper();
        JsonNode j = mapper.readTree(new File("information.json"));
        InformationModel m = new InformationModel();
        m.setType(j.get("information").get("type").textValue());
        m.setDate(j.get("information").get("date").textValue());
        m.setName(j.get("information").get("user").get("name").textValue());
        m.setLastName(j.get("information").get("user").get("lastName").textValue());        
        mapper.writeValue(new File("outputfile.json"), j);
    }
}

答案 2 :(得分:1)

您可以使用Gson。有一个很好的教程here 您可以利用自定义序列化。

如果您想使用当前的POJO结构,请按照以下步骤操作: 用于反序列化json的代码

    GsonBuilder gsonBuilder = new GsonBuilder();

JsonDeserializer<UserDate> deserializer = InformationModelDeserializer() ; 
// implementation detail  
gsonBuilder.registerTypeAdapter(InformationModel .class, deserializer);

Gson customGson = gsonBuilder.create();  
InformationModel customObject = customGson.fromJson(yourJson, InformationModel .class);  

InformationModelDeserializer.java的代码

public class InformationModelDeserializer implements JsonDeserializer<InformationModel > {  
@Override
public InformationModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    //intercept the json to convert it to your desired shape
    JsonObject jsonObject = json.getAsJsonObject();
    JsonObject userJsonObject json.getAsJsonObject("user")


    return new InformationModel (
        userJsonObject.get("name").getAsString(),
        userJsonObject.get("lastname").getAsString(),
        jsonObject.get("type").getAsString(),
        jsonObject.get("date").getAsString(),

    );
}
}

最后将这个@anotaion放在InformationModel类@JsonAdapter(InformationModelDeserialize.class)

之前

或轻松将您的POJO更改为

Information.java

public class Information {
    private String type;
    private String date;

    private User user;

    //.....
}

User.java

public class User {
    private String name;
    private String lastName;

  // .....
 }

并轻松实现:

Information info=new Gson().fromJson(yourJson,Information.class);

答案 3 :(得分:0)

因此,似乎唯一的解决方案是使用与JSON相同的类结构(为了便于阅读而省略了导入和包):

<强> InformationModel.java

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InformationModel {
    private Information information;

    //Getter and Setter
}

<强> Information.java

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Information {
    private String type;
    private String date;

    private User user;

    //Getters and Setters
}

<强> User.java

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
    private String name;
    private String lastName;

    //Getters and Setters
}