NewCodeLearner
NewCodeLearner

Reputation: 738

how to convert hashMap to Json file

I am leaning Java.

I have to transfer a Hashmap to Server using rpc.

HashMap

Map<String, String> testMap = new HashMap<String, String>();
testMap .put("1", "abc");
testMap .put("2", "ezc");
testMap .put("3", "afc");
testMap .put("4", "cvc");
..

how to do that.

Upvotes: 7

Views: 28259

Answers (4)

Prso
Prso

Reputation: 92

See this link if its helps..

http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
Map<String, String> testMap = new HashMap<String, String>(); 
testMap .put("1", "abc"); 
testMap .put("2", "ezc"); 
testMap .put("3", "afc"); 
testMap .put("4", "cvc"); 

      mapper.writeValue(new File("c:\\user.json"), testMap);

Upvotes: 7

Alain BUFERNE
Alain BUFERNE

Reputation: 2071

I don't catch : HashMap is Serializable so should be able to be used between client and server?

Upvotes: 2

Byter
Byter

Reputation: 1132

you can also try GSON library. It is fast and easy to use. The Below wrapper class will make your job even more easy

public class ConvertJsonToObject {

    private static Gson gson = new GsonBuilder().create();

    public static final <T> T getFromJSON(String json, Class<T> clazz) {
        return gson.fromJson(json, clazz);
    }

    public static final <T> String toJSON(T clazz) {
        return gson.toJson(clazz);
    }
}

All you need to do is

Map<String, String> testMap = new HashMap<String, String>();
testMap .put("1", "abc");
testMap .put("2", "ezc");
testMap .put("3", "afc");
testMap .put("4", "cvc");
String json = ConvertJsonToObject.toJSON(testMap);

and you can easily get your original Object back on the other side

Map<String, String> newTestMap = ConvertJsonToObject.getFromJSON(json,Map.class);

Upvotes: 4

Steve Kuo
Steve Kuo

Reputation: 63084

Take a look at Jackson JSON processor. In particular the code will look something like:

Map map = your map
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);

If you want pretty JSON (multiple lines) for debugging, then use:

String json = mapper.defaultPrettyPrintingWriter().writeValueAsString(map);

Upvotes: 12

Related Questions