Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert hashMap to Json file

Tags:

java

gwt

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.

like image 723
NewCodeLearner Avatar asked Aug 07 '12 18:08

NewCodeLearner


People also ask

Can we convert map to JSON?

We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple. JSONValue.

Is JSON a HashMap?

JSON is a text based object that different from HashMap.

What is map object in JSON?

You can map the data types of your business model into JSON by using the examples. Data in JSON is either an object or an array. A JSON object is an unordered collection of names and values. A JSON array is an ordered sequence of values. A value can be a string, a number, a Boolean, a null, an object, or an array.

Can we convert JSON to map in Java?

We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.


1 Answers

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);
like image 106
Steve Kuo Avatar answered Oct 22 '22 08:10

Steve Kuo