2

I want to parse json from a server and place it into a class. I use json4s for this. The issue is that a json object contains too many fields, it's about 40-50 of them, some of them have the long names.

I wonder, what will be a sensible way to store all of them, will I have to create 40-50 fields in a class? Remember, some of them will have the long names, as I said earlier.

I use Scala, but a Java's approach might be similar to it, so I added a tag of Java also.

Alan Coromano
  • 22,006
  • 44
  • 122
  • 184

2 Answers2

1

I don't know json4s but in Jersey with Jackson, for example, you can use a Map to hold the Json data or you can use a POJO with all those names.

Sometimes its better to have the names. It makes the code much easier to understand.

Sometimes its better to use a Map. For example, if the field names change from time to time.

If I recall it correctly, using pure Jackson you do something like this:

String jsonString = ....; // This is the string of JSON stuff
JsonFactory factory = new JsonFactory(); 
ObjectMapper mapper = new ObjectMapper(factory);  // A Jackson class
Map<String,Object> data = mapper.readValue(jsonString, HashMap.class); 

You can use a TypeReference to make it a little cleaner as regards the generics. Jackson docs tell more about it. There is also more here: StackOverflow: JSON to Map

Community
  • 1
  • 1
Lee Meador
  • 12,221
  • 1
  • 29
  • 38
1

There are generally two ways of parsing json to object 1) Parse json to object representation. the other which might suit you as you mention that your object has too many fields is amap/hashtable, or you could just keep it as JObject, an get fields ehrn you need them

varun
  • 3,910
  • 29
  • 28
  • how do I get them from JObject and why is it more convenient? – Alan Coromano Jun 04 '13 at 17:18
  • look here http://www.scala-lang.org/api/current/index.html#scala.util.parsing.json.JSONObject returns a map in val – varun Jun 04 '13 at 17:18
  • its convenient as you cast the object directly to a wrapper like [parse(""" { "numbers" : [1, 2, 3, 4] } """) ]which in turn allows you access to a key value like relation ship, I had used a similar technique in json.net. There isn't much difference really. – varun Jun 04 '13 at 17:22