Priyank
Priyank

Reputation: 14387

Convert JSON String to Java Object or HashMap

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

Upvotes: 2

Views: 10514

Answers (4)

Elliott Hughes
Elliott Hughes

Reputation: 4665

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.

Upvotes: 1

alexanderblom
alexanderblom

Reputation: 8622

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)

Upvotes: 3

yanchenko
yanchenko

Reputation: 57216

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

Upvotes: 2

BalusC
BalusC

Reputation: 1109685

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.

Upvotes: 5

Related Questions