7

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.

NewCodeLearner
  • 738
  • 3
  • 14
  • 38

4 Answers4

12

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);
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
7

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);
sP_
  • 1,738
  • 2
  • 15
  • 29
Prso
  • 92
  • 7
4

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);
Byter
  • 1,132
  • 1
  • 7
  • 12
2

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

Alain BUFERNE
  • 2,016
  • 3
  • 26
  • 37