How to Inconvert JSON String and Map in Java


In this example we will show how to inconvert JSON string and Map.

Source Code

(1)Convert JSON string to Map

package com.beginner.examples;

import java.util.Map;

import com.alibaba.fastjson.JSON;

public class JsonToMap {

	public static void main(String[] args) {
		String jsonStr =  "{"id":"1","age":"10","name":"Alice","code":"20180806654765"}";
		Map map = JSON.parseObject(jsonStr,Map.class);
		
		System.out.println("Age:" + map.get("age"));
		System.out.println("Name:"+map.get("name"));
		System.out.println("Number:" + map.get("code"));
	}

}

Output:

Age:10
Name:Alice
Number:20180806654765

(2)Convert Map to Json String

package com.beginner.examples;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

public class MapToJson {

	public static void main(String[] args) {
		Map map = new HashMap();
		map.put("name", "Bob");
		map.put("age", "12");
		map.put("code", "20180806654766");
		
		String jsonStr = JSON.toJSONString(map);
		System.out.println("Map To JSon:" + jsonStr);

	}
}

Output:

Map To JSon:{"code":"20180806654766","name":"Bob","age":"12"}

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments