将符合json格式的字符串转换为json对象或者是json数组
需要的jar包
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
測試代碼:
@Test
public void myTest(){
String jsonString="{'name':'小明','age':'15','school':'scu'}";
JSONObject jsonObject = JSON.parseObject(jsonString, JSONObject.class);
System.out.println(jsonObject);
}
測試結果:
測試代碼
@Test
public void myTest() {
String jsonMessage = "[" +
"{'num':'1', '外语':88, '历史':65, '地理':99, 'object':{'k1':'1111','k2':'2222','k3':'3333'}}," +
"{'num':'2', '外语':58, '历史':45, '地理':19, 'object':{'k1':'2222','k2':'2222','k3':'3333'}}," +
"{'num':'3', '外语':98, '历史':62, '地理':39, 'object':{'k1':'3333','k2':'2222','k3':'3333'}}" +
"]";
JSONArray jsonArray = JSON.parseArray(jsonMessage);
for(int i=0;i
測試結果:
import java.util.Date;
public class person {
private String name;
private int age;
private String school;
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
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 String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
", age=" + age +
", school='" + school + '\'' +
", date=" + date +
'}';
}
}
测试代码:
@Test
public void TestJavaBean(){
//person01里面除了包含person.class所有属性,还包含address属性
String person01 = "{'name':'李华','age':'15','school':'scu','date':'2019-04-26','address':'四川省成都市一环路'}";
person perObj01 = JSON.parseObject(person01, person.class);
System.out.println("fastJson自动映射对应属性,多余的属性默认会被忽略:");
System.out.println("perObj01: "+perObj01);
}
测试代码:
@Test
public void TestJavaBean(){
String person02 = "{'name':'张三','age':'18','date':'2019-04-26','address':'四川省成都市一环路','interest':'足球'}";
person perObj02 = JSON.parseObject(person02, person.class);
System.out.println("fastJson自动映射对应属性,没找到的属性为空:");
System.out.println("perObj02: "+perObj02);
}
修改javaBean里面的person.class:
public class person {
@JSONField(name = "myName")
private String name;
@JSONField(name = "sage")
private int age;
@JSONField(name = "college")
private String school;
@JSONField(name = "time")
private Date date;
测试代码:
@Test
public void TestJavaBean(){
String person03 = "{'myName':'王五','sage':'21','college':'scu','time':'2019-04-26'}";
System.out.println("fastJson会严格按照注解自动找寻映射的属性,这时候字符串属性值要和注解一致而不是和java类一致:");
System.out.println("person03: "+person03);
}
字符串可能不符合json的格式,在使用fastjson之前一定要确保你的字符串符合json格式!
提供一个网站可以快速查询指定字符串是否符合json字符串,链接地址:http://www.bejson.com/