如何使用杰克逊

时间:2019-09-25 11:16:35

标签: java json jackson

我可以访问一个RESTful API,该API返回JSON字符串,例如:

{
    "Container1": {
        "active": true
    },
    "Container2": {
        "active": false
    },
}

问题在于RESTful API的设计有点不正确。字段名称已经包含数据。使用Jackson库,无法将字段名称反序列化为相应的Java bean类的属性名称。我认为,这不是JSON规范所没有的。上面的JSON字符串需要反序列化为以下类的实例:

public class Container {
    private Boolean active;
    private String name;
}

对于字段UnrecognizedPropertyException,我最终得到了Container1

我想配置为忽略未知属性,并为该属性提供JsonDeserializer,如下所示:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Container {
    private Boolean active;
    private String name;

    @JsonDeserialize(using = FieldNameToPropertyDeserializer.class)
    public void setName(String name) {
        this.name = name;
    }
}

FieldNameToPropertyDeserializer

public class FieldNameToPropertyDeserializer extends StdDeserializer<String> {
    public FieldNameToPropertyDeserializer() {
        super(String.class);
    }

    @Override
    public String deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        return parser.getCurrentName();
    }
}

反序列化的调用如下:

String jsonString = response.readEntity(String.class);
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader readerFor = objectMapper.readerFor(Container.class);
MappingIterator<Container> mappingIterator = readerFor.readValues(jsonString);
while (mappingIterator.hasNext()) {
    Container container = (Container) mappingIterator.next();
    containers.add(container);
}

但是我只收到空对象(属性设置为null),因为自从设置@JsonIgnoreProperties(ignoreUnknown = true)以来,属性的解析被跳过了。

这有可能吗?还是应该在事后实施类似的后处理?

2 个答案:

答案 0 :(得分:2)

如何?像这样创建一个类ContainerActive

public class ContainerActive {
    private  boolean active;
    // constructors, setters, getters
}

您可以做

  Map<String, ContainerActive> map = mapper.readValue(jsonString, new TypeReference<Map<String, ContainerActive>>() {});

通过此操作,您将具有“ Container1”,“ Container2”作为键,而ContainerActive Object作为具有活动字段的值。

答案 1 :(得分:1)

一种快速的解决方案,如果对象是这样,那么所有对象都是一个容器对象,您可以在其中接收JSON,并可以在下面的代码中使用JSONObject

import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestSO {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, JSONException, IOException {
        String jsonString = "{\r\n" + 
                "    \"Container1\": {\r\n" + 
                "        \"active\": true\r\n" + 
                "    },\r\n" + 
                "    \"Container2\": {\r\n" + 
                "        \"active\": false\r\n" + 
                "    },\r\n" + 
                "}";

        JSONObject jsonObject = new JSONObject(jsonString);

        ObjectMapper mapper = new ObjectMapper();
        for (String key : jsonObject.keySet()) {
            Container container = mapper.readValue(jsonObject.get(key).toString(), Container.class);
            System.out.println(container);
        }   
    }

    static class Container{
        private String name;
        private Boolean active;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Boolean getActive() {
            return active;
        }
        public void setActive(Boolean active) {
            this.active = active;
        }
        @Override
        public String toString() {
            return "Container [name=" + name + ", active=" + active + "]";
        }
    }
}