Java:JSON和Map相互转换

Java:JSON与Map相互转换


需要jar包:jackson-core-2.6.0.jar,jackson-databind-2.6.0.jar,jackson-annotations-2.6.0.jar

1. JSON String to Map

package com.inspur.trc.util;

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

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Json2Map {
	public static void main(String[] args) {
		String json = "{\"name\":\"zitong\", \"age\":\"26\"}";
		Map map = new HashMap();
		ObjectMapper mapper = new ObjectMapper();
		
		try{
			map = mapper.readValue(json, new TypeReference>(){});
			System.out.println(map);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
运行结果:
{age=26, name=zitong}

2. Map to JSON String

package com.inspur.trc.util;

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

import com.fasterxml.jackson.databind.ObjectMapper;

public class Map2Json {
	public static void main(String[] args){
		try{
			ObjectMapper mapper = new ObjectMapper();
			String json = "";
			
			Map map = new HashMap();
			map.put("name", "zitong");
			map.put("age", "26");
			
			json = mapper.writeValueAsString(map);
			
			System.out.println(json);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
运行结果:
{"age":"26","name":"zitong"}

3. Map to JSON File

package com.inspur.trc.util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Map2JsonFile {
	public static void main(String[] args) {
		ObjectMapper mapper = new ObjectMapper();
		Map map = new HashMap();
		map.put("name", "zitong");
		map.put("age", 29);

		List list = new ArrayList();
		list.add("music");
		list.add("football");

		map.put("hobby", list);

		try {
			mapper.writeValue(new File("F:/user.json"), map);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}运行结果:F:/user.json 
  
{"age":29,"name":"zitong","hobby":["music","football"]}

4. JSON File To Map

package com.inspur.trc.util;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonFile2Map {
	public static void main(String[] args) {

		try{
			ObjectMapper mapper = new ObjectMapper();
			
			Map map = mapper.readValue(new File("F:/user.json"),new TypeReference>(){});
			
			System.out.println("name: " + map.get("name"));
			System.out.println("age: " + map.get("age"));
			
			@SuppressWarnings("unchecked")
			List list = (List)map.get("hobby");
			System.out.print("hobby: ");
			for(String str : list){
				System.out.print(str+ " ");
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
运行结果:
name: zitong
age: 29
hobby: music football 



你可能感兴趣的:(Java,Web开发)