将json映射到Object

时间:2018-02-08 14:00:10

标签: java

我正在尝试映射看起来像这样的json响应

{
  "0" : "name",
  "1" : "school",
  "2" : "hobby",
  "3" : "bank",
  "4" : "games"
}

json响应是dyanamic,并且可以包括其他字段,具体取决于它的调用方式,因此我无法使用

public class InfoWareAPIResponse {

    private String name; 
    private String school;

    //getters and setters 
} 

请问如何创建一个可以将这样的json对象映射到??

的类

1 个答案:

答案 0 :(得分:0)

你可以像这样使用java pojo。

package com.something;

import com.fasterxml.jackson.annotation.*;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({})
public class InfoUnAwareAPIResponse {
    @JsonIgnore
    @Valid
    private Map<String, Object> additionalProperties = new HashMap();

    public InfoUnAwareAPIResponse() {
    }

    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    public int hashCode() {
        return (new HashCodeBuilder()).append(this.additionalProperties).toHashCode();
    }

    public boolean equals(Object other) {
        if (other == this) {
            return true;
        } else if (!(other instanceof InfoUnAwareAPIResponse)) {
            return false;
        } else {
            InfoUnAwareAPIResponse rhs = (InfoUnAwareAPIResponse) other;
            return (new EqualsBuilder()).append(this.additionalProperties, rhs.additionalProperties).isEquals();
        }
    }
}

像这样的marshel字符串

public static void main(String args[]) throws IOException {
    InfoUnAwareAPIResponse in = mapJsonToObject("{\"hello\":\"world\"}", InfoUnAwareAPIResponse.class);
    System.out.print("" + in.toString());
}

public static <T> T mapJsonToObject(String input, Class<T> clazz) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    T requestedClass = objectMapper.readValue(input, clazz);
    return requestedClass;
}

我运行了上面的代码,它对我来说很好。