JSON与对象、集合之间的转换1. JSON 格式
对象格式
{"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串
对象数组格式
[{"name":"JSON","address":"北京市西城区","age":25},{"name":"JSON","address":"北京市西城区","age":25}]//对象数组2. java 对象转 JSON 字符串
fastjson
json-lib
//1、使⽤JSONObject
JSONObject json = JSONObject.fromObject(stu);
//2、使⽤JSONArray
JSONArray array=JSONArray.fromObject(stu);
String String();
String String();
3. JSON字符串转 java对象
fastjson
String stuString = "{\"age\":2,\"name\":\"编程⼤道\",\"sex\":\"m\"}";
//JSON字符串转换成Java对象
Student student1 = JSONObject.parseObject(stuString, Student.class);
json-lib
JSONObject jsonObject=JSONObject.fromObject(objectStr);
Student stu=(Bean(jsonObject, Student.class);
/
/2、使⽤JSONArray
JSONArray jsonArray=JSONArray.fromObject(arrayStr);
//获得jsonArray的第⼀个元素
Object (0);
JSONObject jsonObject2=JSONObject.fromObject(o);
Student stu2=(Bean(jsonObject2, Student.class);
4. list 转 json字符串
json-lib
//1、使⽤JSONObject
// JSONObject listObject=JSONObject.fromObject(lists);
//2、使⽤JSONArray
JSONArray listArray=JSONArray.fromObject(lists);
5. json字符串转 list(json-lib)
从上⾯的例⼦可以看出list的对象只能转化为数组对象的格式
//转化为list
List<Student> list2=(List<Student>)List(JSONArray.fromObject(arrayStr), Student.class);
//转化为数组
Student[] ss =(Student[])Array(JSONArray.fromObject(arrayStr),Student.class);
6. map 转 json字符串(json-lib)
//1、JSONObject
JSONObject mapObject=JSONObject.fromObject(map);
//2、JSONArray
JSONArray mapArray=JSONArray.fromObject(map);
7. json字符串转 map(json-lib)
String strObject="{\"first\":{\"address\":\"中国上海\",\"age\":\"23\",\"name\":\"JSON\"}}";
//JSONObject
JSONObject jsonObject=JSONObject.fromObject(strObject);
Map map=new HashMap();
map.put("first", Student.class);
//使⽤了toBean⽅法,需要三个参数
MyBean my=(Bean(jsonObject, MyBean.class, map);
System.out.First());
MyBean
import java.util.Map;
import com.study.day3.Student;
public class MyBean {
private Student first;
public Student getFirst() {
return first;
}
public void setFirst(Student first) {
this.first = first;
}
}
8.  JSON对象-->JSON字符串(fastjson)  json值的类型有哪些
Student stu = new Student("编程⼤道", "m", 2);
//先转成JSON对象
JSONObject jsonObject = (JSONObject) JSON(stu);
//JSON对象转换为JSON字符串
String jsonString = JSONString();
9.JSON对象-->Java对象(fastjson) 
Student stu = new Student("编程⼤道", "m", 2);
//先转成JSON对象
JSONObject jsonObject = (JSONObject) JSON(stu);
//JSON对象转换成Java对象
Student student = JavaObject(jsonObject, Student.class);
10. JSON字符串-->JSON对象(fastjson) 
String stuString = "{\"age\":2,\"name\":\"编程⼤道\",\"sex\":\"m\"}";
//JSON字符串转换成JSON对象
JSONObject jsonObject1 = JSONObject.parseObject(stuString);
  使⽤toBean()⽅法是传⼊了三个参数,第⼀个是JSONObject对象,第⼆个是MyBean.class,第三个是⼀个Map对象。通过MyBean可以知道此类中要有⼀个first的属性,且其类型为Student,要和map中的键和值类型对应,即,first对应键 first类型对应值的类型。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。