1

I have the following class

class MyList{
 List<String> names ;
}

and a Json structure

{
 "names" :[
     {"name":"John"},
     {"name":"David"}
  ]
}

As you can see the JSON structure isn't exactly mapping the class structure.

Is there an easy way to map the json to the desired class?

So per say the following:

    Namese names = new Gson().fromJson(json, Names.class);
    System.out.println(new Gson().toJson(names);

will printout :

["John","David"]

If there isn't a way using Gson, is there any other library that let's me do it easily?

NOTE

by using word easy I mean without manually looping through our json structure and create the class.

nafas
  • 5,283
  • 3
  • 29
  • 57
  • What do you need? Parsing the JSON to Java objects or serialiazing Java objects to JSON...or both? – C.Champagne Nov 07 '17 at 15:39
  • @C.Champagne I'm looking for an easy way to convert a json to Java that their structure aren't exactly the same – nafas Nov 07 '17 at 15:44
  • 1
    No, there is no easy/one-line-of-code way. You need to modify the model or create custom adapter for names property – Volodymyr Baydalka Nov 07 '17 at 15:50
  • As Vlodomyr pointed, I don't think there is an *easy* way, as you meant at least. Can't you adapt your JSON or your class to make them match? (I suppose you would have done it if you could but...who knows?) – C.Champagne Nov 07 '17 at 16:44
  • Either you follow the conventions or you go low level. https://stackoverflow.com/questions/6014674/gson-custom-deseralizer-for-one-variable-in-an-object – Admit Nov 07 '17 at 17:00
  • @C.Champagne I've been just trying to be lazy and make use of our current legacy data source. seems there is no way around it – nafas Nov 08 '17 at 10:16

0 Answers0