首页 > 代码库 > Json字符串转换为java对象
Json字符串转换为java对象
1. Json字符串转换为java对象
1.1. Json字符串转换为java bean
Json2Bean.java |
package jackson;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
public class Json2Bean {
public static void main(String[] args)throws IOException{
String jsonStr = "{\"name\":\"Morris\",\"age\":\"22\",\"sex\":\"男\"}";
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(jsonStr, Person.class);
System.out.println(person); }
}
|
1.2. Json字符串转换为java List集合
Json2List.java |
package jackson;
import java.io.IOException; import java.util.LinkedHashMap; import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
public class Json2List {
public static void main(String[] args)throws IOException {
String jsonStr = "[{\"name\":\"Bob\",\"age\":\"33\",\"sex\":\"女\"}," + "{\"name\":\"Morris\",\"age\":\"22\",\"sex\":\"男\"}]";
ObjectMapper mapper = new ObjectMapper();
List<LinkedHashMap<String, String>> list = mapper.readValue(jsonStr, List.class);
for (LinkedHashMap<String, String> linkedHashMap : list) { for (String key:linkedHashMap.keySet()) { System.out.println(key+":"+linkedHashMap.get(key)); } } }
}
|
运行结果如下:
name:Bob
age:33
sex:女
name:Morris
age:22
sex:男
1.3. Json字符串转换为java Map集合
Json2Map.java |
package jackson;
import java.io.IOException; import java.util.Map; import java.util.Set;
import org.codehaus.jackson.map.ObjectMapper;
public class Json2Map {
public static void main(String[] args)throws IOException {
String jsonStr = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+ "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(jsonStr, Map.class);
Set keySet = map.keySet();
for (Object key : keySet) { System.out.println(key+":"+map.get(key)); }
}
}
|
运行结果如下:
success:true
A:{address=address2, name=haha2, id=2,email=email2}
B:{address=address, name=haha, id=1,email=email}
1.4. Json字符串转换为数组
Json2Array.java |
package jackson;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
public class Json2Array {
public static void main(String[] args)throws IOException {
String jsonStr = "[{\"name\":\"Bob\",\"age\":\"33\",\"sex\":\"女\"}," + "{\"name\":\"Morris\",\"age\":\"22\",\"sex\":\"男\"}]";
ObjectMapper mapper = new ObjectMapper();
Person[] persons = mapper.readValue(jsonStr, Person[].class);
for (Person person : persons) { System.out.println(person); }
}
}
|
运行结果如下:
Person [name=Bob, age=33, sex=女]
Person [name=Morris, age=22, sex=男]
Json字符串转换为java对象