最近在看JSON,JSONObject和JSONArray。故用这个文章来记录一下学习内容。
直接上代码:下面的是主要将一些对象、String、Map、List转为JSONObject、JSONArray的:
//将student转为JSONObject
Student student =new Student("1",1);
String json = JSON.toJSONString(student);
JSONObject jsonObject = JSONObject.parseObject(json);
//将String转为JSONObject
String str = "{数据:1}";
JSONObject jsonObject1 = JSONObject.parseObject(str);
//将map转为JSONObject
Map<String,Integer> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
String s3 = JSONObject.toJSONString(map);
JSONObject jsonObject3 = JSONObject.parseObject(s3);
//将List转为JSONObject
Student s1 = new Student("1", 1);
Student s2 = new Student("2", 2);
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
String s = JSONArray.toJSONString(list);
JSONArray jsonArray = JSONArray.parseArray(s);
//将String转为JSONArray
String str1 = "[{数据:1}]";
JSONArray jsonArray1 = JSONArray.parseArray(str1);
下面的是主要将一些JSONObject、JSONArray转为String、map、Object的;
//JSONArray转为list
List<Student> lists = JSONArray.toJavaObject(jsonArray,List.class);
//JSONObject转为Map
Map<String,Integer> maps = JSONObject.parseObject(s3, Map.class);
//JSONObject转为对象
Student student1 = JSONObject.toJavaObject(jsonObject2, Student.class);
上面的也许有些乱这下面是我测试的全部代码。
package com.example.demo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.lang.reflect.Type;
import java.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import static com.alibaba.fastjson.parser.ParserConfig.global;
public class Test {
public static void main(String[] args) {
//将student转为JSONObject
Student student =new Student("1",1);
String json = JSON.toJSONString(student);
JSONObject jsonObject = JSONObject.parseObject(json);
//将String转为JSONObject
String str = "{数据:1}";
JSONObject jsonObject1 = JSONObject.parseObject(str);
//将map转为JSONObject
Map<String,Integer> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
String s3 = JSONObject.toJSONString(map);
JSONObject jsonObject3 = JSONObject.parseObject(s3);
//将List转为JSONObject
Student s1 = new Student("1", 1);
Student s2 = new Student("2", 2);
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
String s = JSONArray.toJSONString(list);
JSONArray jsonArray = JSONArray.parseArray(s);
System.out.println(jsonArray);
//将String转为JSONArray
String str1 = "[{数据:1}]";
JSONArray jsonArray1 = JSONArray.parseArray(str1);
System.out.println(jsonArray1);
//JSONArray转为list
List<Student> lists = JSONArray.toJavaObject(jsonArray,List.class);
System.out.println(lists.get(0));
Map<String,Integer> maps = JSONObject.parseObject(s3, Map.class);
System.out.println(maps);
Student s4 = new Student("4", 4);
String s5 = JSONObject.toJSONString(s4);
JSONObject jsonObject2 = JSONObject.parseObject(s5);
Student student1 = JSONObject.toJavaObject(jsonObject2, Student.class);
System.out.println(student1);
}
}