22554

Parse jsonObject when field names are unknowm

Question:

I'm trying to extract some data from a JsonObject. The problem is that the fields that come inside that json have unpredictable names.

How can I extract that information having this weird field names?

Here is an example:

"myObject":{ "216cfa89a2de57554b36b177f0bfbb05":{ }, "0cf9182b5ceba2cb64174141a13e647d":{ }, "eb1d1b19e117ba1387a798d9194b4660":{ }, "157b52871e8e560c7ec0be111ef02363":{ }, "4db69dd3a8ae8e0089bd2959ab0c5f86":{ }, }

I'm using gson, where we have the method getAsJsonObject, but how can I use it if I don't know the field names?

JsonObject jsonObject= myObjectJsonObject.getAsJsonObject("???");

Also, there can be a variable number of fields, and this is a problem too. I wonder why I don't get an jsonArray as a response, it would be more suitable and I could have parse it that way.

Answer1:

Use the <a href="http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/JsonObject.html#entrySet()" rel="nofollow">JsonObject.entrySet()</a>.

String json = "{ 'abcd': { 'a':'d' }, 'dcba': { 'd':'a' } }"; JsonObject o = new JsonParser().parse(json).getAsJsonObject(); for(Map.Entry<String, JsonElement> entry : o.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue()); }

Or you could get a map when you load the object:

Map<String, JsonObject> map = new Gson().fromJson(json, new TypeToken<Map<String, JsonObject>>(){}.getType()); for(Map.Entry e : map.entrySet()) { System.out.println(e.getKey()); System.out.println(e.getValue()); } }

Or you could add a <a href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html" rel="nofollow">JsonDeserializer</a> which can deserialize your class into something sensible (likely a map).

Answer2:

In your case its beter to use <a href="https://github.com/jayway/JsonPath" rel="nofollow">JsonPath</a>

With JSON like this :

{ "myObject": { "216cfa89a2de57554b36b177f0bfbb05": { "field1": true }, "0cf9182b5ceba2cb64174141a13e647d": { "field2": true }, "eb1d1b19e117ba1387a798d9194b4660": { "field3": true }, "157b52871e8e560c7ec0be111ef02363": { "field2": true }, "4db69dd3a8ae8e0089bd2959ab0c5f86": { "field5": true } } }

And an expretion of JsonPth

$.myObject.*

You will get an array of fields

[ { "field1": true }, { "field2": true }, { "field3": true }, { "field2": true }, { "field5": true } ]

Hope that help :)

Answer3:

JsonObject o = new JsonParser().parse("some json string").getAsJsonObject();

Answer4:

If you look at <a href="https://stackoverflow.com/questions/6455303/dealing-with-randomly-generated-and-inconsistent-json-field-key-names-using-gson/7618260#7618260" rel="nofollow">this</a> post you see that you can simply do:

Object o = new Gson().fromJson(json, Object.class);

The object returned is a Map of String and either String or a Map.

Recommend

  • Cordova 2.7.0 PushPlugin “cordova cannot be resolved” and “ctx cannot be resolved”
  • Showing Error :Attempt to invoke interface method 'int java.util.List.size()' on a null ob
  • Android: convert Parcelable to JSON
  • JSON Array to ImageView in GridView
  • How to handle the JAVA WatchService Overflow event?
  • Haskell: List Created Evaluating List Elements
  • Get max ID and min ID from specific column in MySQL php
  • Get entry assembly from ASP.NET application [duplicate]
  • Update varbinary(MAX) field in SQLServer 2012 Lost Last 4 bits
  • Generate random number from custom distribution
  • Firefox Extension - Monitor refresh and change of tab
  • Remove final comma from string in vb.net
  • Declaring variable dynamically in VB.net
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • azure media services - The request body is too large and exceeds the maximum permissible limit
  • Sencha Touch 2.0 Controller refs attribute not working?
  • Play WS (2.2.1): post/put large request
  • Get data from AJAX - How to
  • C++ Partial template specialization - design simplification
  • Initializer list vs. initialization method
  • Is there a javascript serializer for JSON.Net?
  • Spring security and special characters
  • How to add date and time under each post in guestbook in google app engine
  • Where to put my custom functions in Wordpress?
  • Trying to switch camera back to front but getting exception
  • htaccess rewriting URLs with multiple forward slashes
  • Weird JavaScript statement, what does it mean?
  • How do you troubleshoot character encoding problems?
  • Is there a mandatory requirement to switch app.yaml?
  • How to format a variable of double type
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • Buffer size for converting unsigned long to string
  • AngularJs get employee from factory
  • WPF Applying a trigger on binding failure
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Programmatically clearing map cache
  • Binding checkboxes to object values in AngularJs
  • How to Embed XSL into XML