Nuñito Calzada
Nuñito Calzada

Reputation: 2106

Plain Old Java Objects from JSON or JSON-Schema

I have a Json Object that I want to transform in a POJO, the problem is that 1 of his properties is a value c that will have different values that I don't know in advance. Let's say that I don't know nothing of "$key", or could be names of the cities all over the world

{
    "data": [{
        "id": 1,
        "name": "theName",
        "symbol": "theSymbol",
        "last_updated": "2018-06-02T22:51:28.209Z",
        "quote": {
            "$key": {
                "price": 9283.92,
            },
            "$key": {
                "price": 1,

            }
        }
    }],
    "status": {
        "timestamp": "2018-06-02T22:51:28.209Z",
        "error_code": 0,
        "error_message": "",
        "elapsed": 10,
        "credit_count": 1
    }
}

Upvotes: 1

Views: 263

Answers (3)

Alex Ding
Alex Ding

Reputation: 75

As "$key" is unknown, my suggestion is converting quote to Map<String, Map<String, Integer>>, so that the value of "$key" can be ignored! This is my code:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public class XmlParser {
    static class Entity {
        @JsonProperty("id")
        String id;
        @JsonProperty("name")
        String name;
        @JsonProperty("symbol")
        String symbol;
        @JsonProperty("last_updated")
        String lastUpdated;
        @JsonProperty("quote")
        Map<String, Map<String, Integer>> quote;
    }

    static class Data {
        @JsonProperty("data")
        List<Entity> data;
    }

    public static void main(String[] args) throws Exception {
    final String testJson = "{\"data\":[{\"id\":1,\"name\":\"theName\",\"symbol\":\"theSymbol\",\"last_updated\":\"2018-06-02T22:51:28.209Z\",\"quote\":{\"a\":{\"price\":9283.92},\"b\":{\"price\":1}}}]}";

        ObjectMapper mapper = new ObjectMapper();
        Data data = mapper.readValue(testJson, Data.class);
        System.out.println(mapper.writeValueAsString(data));
    }
}

Upvotes: 1

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31279

You can map $key to a property of type JsonNode. It will have a working equals/hashCode so you can compare it, put it in HashMaps etc without the need to databind it further (JsonNode represents a Json (sub)tree directly.)

Upvotes: 1

cslotty
cslotty

Reputation: 1797

I would solve this differently. I would make it some kind of "meta object", f.ex. like this:

{
....
"unknownType": {
    "name": "$key",
    "value1": "9283.92",
    "value2": "tttt"
    }
}

That way you have eliminated one layer of unknown information! You can try and parse the valueN fields to all different types of values and throw/catch parsing exceptions, and thus find out the correct type.

HTH

Upvotes: 0

Related Questions