How can I read JSON into a list of shared objects in java?

I need to get data from a web service, I am using Jackson, but I have the same problem with Gson, I have no problem with individual objects, but when I get a list of multiple objects, it is not that easy for me.

The resulting JSON looks like this:

{"country":
[
{"code":"AD","nombre":"Andorra","name":"Andorra"},
{"code":"AE","nombre":"Emiratos Árabes Unidos","name":"United Arab Emirates"}
]
}

      

This is a list of my own class CountryWSType

, I have several classes like this and you need a way that can get a list of any of them. I tried to parse it as a list:

List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));

      

Also trying to create a custom list type:

    public class ListWSType<T> implements List<T>{

    private List<T> listaInterna;

    //implents methods
    }

      

But I always get JsonMappingException

, and I have no more ideas on how to do it.

Hope someone can help me.

As some people ask, here is the class I was trying to parse from JSON:

@XmlRootElement(name="country")
@XmlType(propOrder={"code", "nombre", "name"})
public class CountryWSType {

    /** Código ISO */
    @XmlElement(name="code")
    public String code;

    /** Nombre en español */
    @XmlElement(name="nombre")
    public String nombre;

    /** Nombre en inglés */
    @XmlElement(name="name")
    public String name;

    /** Constructor sin parámetros. No inicializa nada...
     * Está para que funcione el marshall/unmarshall.
     */
    public CountryWSType() {}
}

      

Also note that when I put MyClass it means CountryWSType class, sorry for the overlooked errors.

+3


source to share


1 answer


Maybe this will help:

//first convert input string to json array
JSONObject jsonobject = new JSONObject(countriesAsJsonString);

JSONArray jsonArray = jsnobject.getJSONArray("countries");

//then get the type for list and parse using gson as
Type listType = new TypeToken<List<MyClass>>(){}.getType();
List<MyClass> countriesList = new Gson().fromJson(jsonArray, listType);

      



If you say your json arrary elements can be of different types, then it won't know what type of class is to instantiate and you will need to specify an extra attribute in json to indicate that this is an ugly approach, especially if the json is external side. But if this is what you want, than this SO post explains it .

0


source







All Articles