简体   繁体   中英

How to use Jackson to deserialize to list or value based upon JSON?

I have a json in following format, where in key represents the attribute type and value represents the value of that attribute.

{ "attributes":
[
  {
    "key":"name",
    "value":"Archit"
  },
  { 
    "key":"website",
    "value":"stackoverflow"
  },
  { 
    "key":"languages",
    "value":[
              "python",
              "java",
              "c++"
            ]
  }
]
}

I am trying to map it to an following java object using jackson :

public class Attributes {
  List<Attribute> attributes;
}



public abstract class Attribute {
  String key;
}



public class SingleValuedAttribute extends Attribute{
  String value;
}


public class MultiValuedAttribute extends Attribute{
  List<String> value;
}


  ObjectMapper mapper = new ObjectMapper();
  Attributes attributes = mapper.readValue(new File(jsonFilePath), Attributes.class);

I tried having a look at polymorphic deserialization but that required type info in the json object, which doesn't exist in my json ?

Any tips on how to do this ?

PS: I can't change the json format. The list of keys is not bounded/limited.

I do not see the difference between SingleValuedAttribute and MultiValuedAttribute classes. SingleValuedAttribute class represents one element array. You could simplify your POJO classes hierarchy by deleting it.

Please, see below example how it could looks like:

import java.io.File;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonProgram {

    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

        File json = new File("/x/test.json");
        System.out.println(objectMapper.readValue(json, Attributes.class));
    }
}

class Attributes {

    private List<Attribute> attributes;

    //getters, setters
}

class Attribute {

    private String key;
    private List<String> value;

    //getters, setters
}

Above program prints:

[Attribute [key=name, value=[Archit]], Attribute [key=website, value=[stackoverflow]], Attribute [key=languages, value=[python, java, c++]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM