maven依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
1、java 对象(List、Map、javaBean)转 json 字符串
public static void main(String[] args)
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("word");
list.add("six");
//list to jsonString
String jsonSTR1 =JSON.toJSONString(list);
System.out.println(jsonSTR1);
//map to jsonString
Map<String,Object> map =new HashMap<String, Object>();
map.put("key",list);
String jsonSTR2 =JSON.toJSONString(map);
System.out.println(jsonSTR2);
//javaBean to jsonString
Map<String,Integer> car =new HashMap<String, Integer>();
car.put("car1",100000);
car.put("car2",230000);
Person person=new Person();
person.setAge(28);
person.setName("tony");
person.setCar(car);
String jsonSTR3 =JSON.toJSONString(person);
System.out.println(jsonSTR3);
}
2 、JsonString 转 Object 、JSONObject
public static void main(String[] args)
String jsonString="{\"car\": {\"car2\":150000,\"car1\":98000},\"name\":\"tome\",\"age\":30}";
Object object=JSON.parse(jsonString);
System.out.println(object);
JSONObject jsonObject=JSON.parseObject(jsonString);
System.out.println(jsonObject.get("car"));
}
3 、JsonString 转 javaBean
public static void main(String[] args)
String jsonString="{\"car\":{\"car2\":150000,\"car1\":98000},\"name\":\"tome\",\"age\":30}";
JSONObject jsonObject=JSON.parseObject(jsonString);
Person p=JSON.toJavaObject(jsonObject,Person.class);
System.out.println(p.toString());
}
class Person{
private String name;
private int age;
private Map<String,Integer> car;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
public Map<String, Integer> getCar() {return car;}
public void setCar(Map<String, Integer> car) {this.car = car;}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", car=" + car +
'}';
}
}