tags:

views:

1029

answers:

4

Hi.

I am writing an android app. I want to pass some data across the intents/activities and I feel that a conversion to and from JSON is probably a more optimal way at this point. I am able to convert a java hashmap to a json string successfully using JSONObject support.

However i need to convert back this JSON string to a java object or a hashmap. What is the best way to go about it.

Is parcelable really a change worth doing; if I have simple 5 field object? What are the other ways to transfer data between intents.

Cheers

+4  A: 

I recommend to pick Gson for that. It has excellent support for generics and fullworthy Javabeans and really eases the conversion task. In this answer you can find an example to convert a Map<String, String> to JSON and vice versa and in this answer another example to convert a JSON string to a fullworthy Javabean (from Javabean to JSON is pretty simple with gson.toJson(bean).

Other ways to transfer data are XML and serialization, both which have much more overhead than JSON.

BalusC
+1  A: 

You can pass Serializables with Intents, no need for JSON.

alex
+1  A: 

Why not use Bundle as your Map? It can be put in an Intent easily and is basically a glorified typesafe HashMap.

If you still need to use JSON I would recommend Jackson. It's easy and fast (faster than GSON) for converting to and from Java objects (including Maps)

alexanderblom
+1  A: 

JSON is a particularly bad choice if you have numeric data... it'll mangle anything that can't be represented as a double (and even some double values). except where you have to communicate with JavaScript, you should avoid JSON.

Elliott Hughes
This is incorrect. JSON has generic number type, but that can contain plain integral numbers, and it depends on library whether they exposed as floating point or not. And most specifically most Java JSON libraries handle these cleanly and efficiently.Maybe you have had bad experience with some libraries?
StaxMan
that simply isn't true. random example: the json.org implementation is broken in the way i describe.you probably wouldn't want a "fixed" JSON library anyway, because then it would be incompatible with JavaScript itself.
Elliott Hughes