1

I realize this has probably been asked a hundred times but I have searched a lot and can't find specifically what I'm looking for.

Here is what I'd like. Given a string data, I'd like to deserialize into an object obj that doesn't have all the fields predefined. I'd like to just be able to ask for the fields I want such as obj.getString("stringFieldName") or obj.getInt("intFieldName"). I already have gson being used for other things so if it is possible with gson that would be great although not opposed to using another library.

tbeauvais
  • 1,518
  • 4
  • 17
  • 22
  • [This](http://stackoverflow.com/questions/2525042/how-to-convert-a-json-string-to-a-mapstring-string-with-jackson-json) might help. – Giovanni Botta Jul 01 '15 at 19:07
  • @user2864740 The de facto standard for JSON processing is Jackson at this point. I have never met anybody using the JEE API directly. So much for a standard :) – Giovanni Botta Jul 01 '15 at 19:09

3 Answers3

3

The 'standard' Android JSON library (since API 1) already provides such untyped access.

See JSONObject, eg. getInt:

Returns the value mapped by name if it exists and is an int or can be coerced to an int, or throws otherwise.

Unless needing the JSON mapped onto a 'native' Java collection type this is probably the simplest way to achieve the request. It doesn't require any additional libraries.

user2864740
  • 54,112
  • 10
  • 112
  • 187
1

With Jackson library you can annotate data model class with

@JsonIgnoreProperties(ignoreUnknown = true)

and the jacksonconverter will just parse only these fields that you defined. Other will be ignored.

Sebastian Pakieła
  • 2,604
  • 14
  • 24
0

Have you tried using Retrofit from Square? It works with GSON and Java Annotations and it's super easy to set up.

adao7000
  • 3,462
  • 2
  • 25
  • 35