用到的是阿里的json jar包
import com.alibaba.fastjson.JSONObject;
public class TestJson {
public static void main(String[] args) {
// json格式的字符串转javabean
String jsonString = "{\"username\":\"张三\",\"password\":\"123\",\"sex\":\"男\"}";
JSONObject jbo = JSONObject.parseObject(jsonString);
Person req = (Person) JSONObject.toJavaObject(jbo, Person.class);
String password = req.getPassword();
System.out.println(password);
// javabean转json格式的字符串
Person person = new Person();
person.setUsername("李四");
person.setPassword("456");
person.setSex("男");
Object jsonData = JSONObject.toJSON(person);
System.out.println(jsonData.toString());
}
}
运行结果:
123
{"password":"456","sex":"男","username":"李四"}
json形式的对象数组转成java对象
package com.it.fan;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.it.pojo.Grade;
import com.it.pojo.Person;
import com.it.pojo.School;
/**
*
* @Description:
* @author: fyk
* @date: 2019年8月20日
*/
public class StringElementArrayToJson {
public static void main(String[] args) {
String jsonString = "[{\"username\":\"zhangsan\",\"pwd\":\"123\",\"sex\":\"男\"},{\"username\":\"xiaohong\",\"pwd\":\"456\",\"sex\":\"女\"}]";
//json格式的对象数组转成JSONArray
JSONArray parseArray = JSONArray.parseArray(jsonString);
//获得grade数组的大小
Grade[]grades=new Grade[parseArray.size()];
for(int i=0;i<parseArray.size();i++){
//一个对象转成JSONObject
JSONObject object = (JSONObject) parseArray.get(i);
//JSONObject转成javabean
Person javaObject = JSONObject.toJavaObject(object, Person.class);
//person对象放入grade中
Grade grade = new Grade();
grade.setPerson(javaObject);
//往grade书中放入grade
grades[i]=grade;
}
School school = new School();
school.setGrade(grades);
System.out.println(school.toString());
}
}
用到的java实体类(具体参考如下)
package com.it.pojo;
import java.util.Arrays;
public class School {
private Grade[] grade;
public Grade[] getGrade() {
return grade;
}
public void setGrade(Grade[] grade) {
this.grade = grade;
}
@Override
public String toString() {
return "School [grade=" + Arrays.toString(grade) + "]";
}
}
package com.it.pojo;
public class Grade {
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
@Override
public String toString() {
return "Grade [person=" + person + "]";
}
}
package com.it.pojo;
public class Person {
private String username;
private String pwd;
private String sex;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [username=" + username + ", pwd=" + pwd + ", sex=" + sex + "]";
}
}
运行结果:
School [grade=[Grade [person=Person [username=zhangsan, pwd=123, sex=男]], Grade [person=Person [username=xiaohong, pwd=456, sex=女]]]]