0

I'm working on an Android app. The app gets the data as JSON string (name of universities and student lists) and manipulate the app according to the data.

What will be a better approach?

  • Create a new Object and parse the JSON string into it, and work with the object, or
  • Keep the JSON string, and just use JSONObject whenever I need to grab information from the string
  • Or any other way?

If I'm using the new Object, how can I transfer (or share) the object with other activities in the app? I know that for string we can use putextra().

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
Mr. Levy
  • 15
  • 4

4 Answers4

1

Use objects.
I would suggest to use Jackson library, be cause it is very fast and easy to ingrate.
You can find code examples here :
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

P.S. : Jackson is not the only library for this approach > Jackson Vs. Gson

Community
  • 1
  • 1
EvZ
  • 11,889
  • 4
  • 38
  • 76
0

I would recommend parsing the string (or using a library to do this for you!) and filling an object. This way, your model object can control the data and how it is shared with other objects, and use internal data structures to optimize usage. If you stuck with the JSON string you'd end up parsing it multiple times to pull out data.

However you decide to share the object/string across activities shouldn't affect your decision for how to model the data. You'll likely end up passing it across activities in any case.

Mike
  • 2,399
  • 1
  • 20
  • 26
0

I almost always parse the JsonObject into a specific object E.g. class University.

One benefit of doing this, is you can put it nicely into collections. E.g. HashMaps, Set or just straight List. When dealing with it as a JsonObject you won't be able to as easily work with it.

You can do things like sort it if you Object inherits Comparable, and can define equals/toString/hashCode.

There are a number of other benefits, but I think you'll find holding that data in a real data structure will give you the most benefit

Bruce Lowe
  • 6,063
  • 1
  • 36
  • 47
  • Can I pass an object (let's say university) to another activity? – Mr. Levy Feb 05 '13 at 13:24
  • you can - its not completely as trivial as one might hope, but its not too bad: http://stackoverflow.com/questions/5621132/passing-custom-objects-between-activities – Bruce Lowe Feb 05 '13 at 16:48
0

I suggest that you use objects too.

You can use Gson library to do any conversion between json string and objects. It is very, very easy to use. http://code.google.com/p/google-gson/

To transfer the data between other activities you can make your object implement the Serializable interface, this way you can use the .putExtra() and pass it forward.

Renato Lochetti
  • 4,558
  • 3
  • 32
  • 49