01.概述
如果我們接收到的是一個json字符串,我們該如何對該字符串進(jìn)行解析?
- 方式一:使用實(shí)體類進(jìn)行解析
- 方式二:使用map進(jìn)行解析
使用的依賴jar包:fastjson
compile('com.alibaba:fastjson:1.2.xx')
02.對json字符串進(jìn)行解析
使用實(shí)體類進(jìn)行解析
創(chuàng)建一個用于接收的實(shí)體類:使用json字符串中的那些字段,實(shí)體類的屬性值一定要和JSON串中的key
對應(yīng)
假設(shè)JSON字符串如下:
"{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"sex\":\"man\",\"age\":18}"
對應(yīng)的實(shí)體類屬性就應(yīng)該定義成如下的樣子:
public class PersonInfoDto {
private Date bornTime;
private String userName;
private String sex;
private Integer age;
public Date getBornTime() {
return bornTime;
}
public void setBornTime(Date bornTime) {
this.bornTime = bornTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "PersonInfoDto{" +
"bornTime=" + bornTime +
", userName='" + userName + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
代碼示例:
public class test01 {
public static void main(String[] args) {
String jsonStr = "{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"sex\":\"man\",\"age\":18}";
PersonInfoDto personInfoDto = JSONObject.parseObject(jsonStr, PersonInfoDto.class);
System.out.println(personInfoDto.toString());
}
}
運(yùn)行結(jié)果:
PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='AISMALL', sex='man', age=18}
使用實(shí)體類解析拓展
public class test01 {
public static void main(String[] args) {
// json串里面的key與實(shí)體類字段匹配幾個就會賦值幾個,匹配不上的賦值為null
String jsonStr1 ="{\"bornTime\":\"2022-09-30 19:48:59\"}";
PersonInfoDto personInfoDto1 = JSONObject.parseObject(jsonStr1, PersonInfoDto.class);
System.out.println("personInfoDto1: " + personInfoDto1);
// json串中出現(xiàn)重復(fù)的字段,就會使用后者進(jìn)行覆蓋
String jsonStr2 ="{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"userName\":\"AISMALL2\"}";
PersonInfoDto personInfoDto2 = JSONObject.parseObject(jsonStr2, PersonInfoDto.class);
System.out.println("personInfoDto2: " + personInfoDto2);
// json串里面的key與實(shí)體類字段匹配幾個就會賦值幾個,不管該傳有多長,只取匹配到的key的value給實(shí)體類賦值
String jsonStr3 ="{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"sex\":\"man\",\"age\":18,\"age2\":18}";
PersonInfoDto personInfoDto3 = JSONObject.parseObject(jsonStr3,PersonInfoDto.class);
System.out.println("personInfoDto3: " + personInfoDto3);
// 剛好對應(yīng)的情況
String jsonStr4="{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"sex\":\"man\",\"age\":18}";
PersonInfoDto personInfoDto4 = JSONObject.parseObject(jsonStr4, PersonInfoDto.class);
System.out.println("personInfoDto4: " + personInfoDto4);
}
}
運(yùn)行結(jié)果:
personInfoDto1: PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='null', sex='null', age=null}
personInfoDto2: PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='AISMALL2', sex='null', age=null}
personInfoDto3: PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='AISMALL', sex='man', age=18}
personInfoDto4: PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='AISMALL', sex='man', age=18}
小結(jié)
- json串里面的key與實(shí)體類字段匹配幾個就會賦值幾個,不管該傳有多長,只取匹配到的key的value給實(shí)體類賦值,匹配不上的賦值為null。
- json串中出現(xiàn)重復(fù)的字段,就會使用后者進(jìn)行覆蓋。
使用map進(jìn)行解析
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"age\":18,\"sex\":\"man1\",\"userName\":\"AISMALL1\"}";
//====================方式一==============================
Map maps = (Map)JSON.parse(jsonStr);
for (Object map : maps.entrySet()) {
System.out.println(((Map.Entry)map).getKey()+": " + ((Map.Entry)map).getValue());
}
//====================方式二==============================
Map mapTypes =JSON.parseObject(jsonStr);
for(Object obj :mapTypes.keySet()){
System.out.println("key: " + obj + " value: " + mapTypes.get(obj));
}
//====================方式三==============================
Map mapType = JSON.parseObject(jsonStr, Map.class);
System.out.println("這個是用JSON類,指定解析類型,來解析JSON字符串!!!");
for(Object obj :mapType.keySet()){
System.out.println("key: " + obj + " value: " + mapType.get(obj));
}
//====================方式四==============================
Map json =(Map)JSONObject.parse(jsonStr); //用Json對象解析成Map類型
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey() + ": "+((Map.Entry)map).getValue());
}
//====================方式五==============================
JSONObject jsonobject = JSONObject.parseObject(jsonStr);
for(Object map:jsonobject.entrySet()){
System.out.println(((Map.Entry)map).getKey()+": "+((Map.Entry)map).getValue());
}
}
}
03.Map和json字符串的互相轉(zhuǎn)換
3.1.json字符串轉(zhuǎn)換為Map
參考:使用map進(jìn)行解析
3.2.Map轉(zhuǎn)換為json字符串
public class test01 {
public static void main(String[] args) {
// 創(chuàng)建一個Hashmap
Map<String, Object> paraMap = new HashMap();
paraMap.put("userName","AISMALL");
paraMap.put("sex","man");
paraMap.put("age",18);
// 方式一:轉(zhuǎn)換為json字符串
String jsonStr = JSONObject.toJSONString(paraMap);
System.out.println("jsonStr: " + jsonStr);
// 方式二:轉(zhuǎn)換為json字符串
String jsonStr2 = Json.toJson(paraMap);
System.out.println("jsonStr2: " + jsonStr2);
}
}
運(yùn)行結(jié)果:
jsonStr: {"sex":"man","userName":"AISMALL","age":18}
jsonStr2: {"sex":"man","userName":"AISMALL","age":18}
04.json操作的一些小技巧
4.1.json字符轉(zhuǎn)換為實(shí)體類
前面已經(jīng)介紹了:
JSONObject.parseObject(jsonString, PersonInfoDto .class);
4.2.實(shí)體類轉(zhuǎn)json字符串
public class test01 {
public static void main(String[] args) {
Date date = new Date(); // 創(chuàng)建一個Date對象,獲取當(dāng)前時(shí)間
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 指定格式化格式
f.format(date); // 將當(dāng)前時(shí)間袼式化為指定的格式
PersonInfoDto personInfoDto = new PersonInfoDto();
personInfoDto.setBornTime(date);
personInfoDto.setUserName("AISMALL");
personInfoDto.setSex("man");
personInfoDto.setAge(18);
String jsonStr = JSON.toJSONString(personInfoDto);
System.out.println(jsonStr);
}
}
運(yùn)行結(jié)果:
{"age":18,"bornTime":1665113383685,"sex":"man","userName":"AISMALL"}
4.3.json字符串轉(zhuǎn)換為json對象
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"test\":\"test\",\"Result\":[{\"Result1\":\"Result1\",\"Detail1\":\"Detail1\"},{\"Result2\":\"Result2\",\"Detail2\":\"Detail2\"},{\"Result3\":\"Result3\",\"Detail3\":\"Detail3\"}]}";
// json字符串轉(zhuǎn)換為jsonObject
JSONObject jSONObject = JSONObject.parseObject(jsonStr);
System.out.println(jSONObject);
// 根據(jù)Key取出Json對象中的值
String testStr = jSONObject.getString("test");
System.out.println("testStr: " + testStr);
}
}
運(yùn)行結(jié)果:
{"test":"test","Result":[{"Detail1":"Detail1","Result1":"Result1"},{"Detail2":"Detail2","Result2":"Result2"},{"Detail3":"Detail3","Result3":"Result3"}]}
testStr: test
注意:
- Json對象和Json字符串的區(qū)別在于,
Json對象(JSONObject)
里面有很多定義好的方法可以幫助我們根據(jù)Key取出Json對象中的值,后面我們也會演示幾個JSONObject提供的方法。
4.4.json對象轉(zhuǎn)換為json字符串
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"test\":\"test\",\"Result\":[{\"Detail1\":\"Detail1\",\"Result1\":\"Result1\"},{\"Detail2\":\"Detail2\",\"Result2\":\"Result2\"},{\"Detail3\":\"Detail3\",\"Result3\":\"Result3\"}]}";
// json字符串轉(zhuǎn)換為jsonObject
JSONObject jSONObject = JSONObject.parseObject(jsonStr);
// json對象轉(zhuǎn)換為json字符串
String jsonObjectConv = JSON.toJSONString(jSONObject);
System.out.println(jsonObjectConv);
}
}
運(yùn)行結(jié)果:
{"test":"test","Result":[{"Detail1":"Detail1","Result1":"Result1"},{"Detail2":"Detail2","Result2":"Result2"},{"Detail3":"Detail3","Result3":"Result3"}]}
4.5.json字符串?dāng)?shù)組轉(zhuǎn)換json數(shù)組
注意:json字符串?dāng)?shù)組,即String是JSONArray格式的字符串
public class test01 {
public static void main(String[] args) {
// json字符串?dāng)?shù)組
String jsonArr = "[{\"Detail1\":\"Detail1\",\"Result1\":\"Result1\"},{\"Detail2\":\"Detail2\",\"Result2\":\"Result2\"},{\"Detail3\":\"Detail3\",\"Result3\":\"Result3\"}]";
JSONArray jsonArray= JSONArray.parseArray(jsonArr);
// 轉(zhuǎn)換成Json字符串?dāng)?shù)組之后,就可以遍歷了,字符串是無法遍歷的
for (Object jsonStr:jsonArray) {
System.out.println(jsonStr);
}
}
}
運(yùn)行結(jié)果:
{"Detail1":"Detail1","Result1":"Result1"}
{"Detail2":"Detail2","Result2":"Result2"}
{"Detail3":"Detail3","Result3":"Result3"}
4.6.List<實(shí)體類>轉(zhuǎn)json數(shù)組
public class test01 {
public static void main(String[] args) {
PersonInfoDto personInfoDto1 = new PersonInfoDto();
personInfoDto1.setUserName("AISMALL1");
personInfoDto1.setSex("man1");
personInfoDto1.setAge(18);
PersonInfoDto personInfoDto2 = new PersonInfoDto();
personInfoDto2.setUserName("AISMALL2");
personInfoDto2.setSex("man2");
personInfoDto2.setAge(19);
List<PersonInfoDto> list = new ArrayList<>();
list.add(personInfoDto1);
list.add(personInfoDto2);
// 轉(zhuǎn)換為json字符串
String jsonStr = JSONObject.toJSONString(list);
System.out.println("jsonStr: " + jsonStr);
// json字符串轉(zhuǎn)換為json數(shù)組
JSONArray jsonArray= JSONArray.parseArray(jsonStr);
// 轉(zhuǎn)換成Json字符串?dāng)?shù)組之后,就可以遍歷了,字符串是無法遍歷的
for (Object jsonStr1:jsonArray) {
System.out.println(jsonStr1);
}
}
}
運(yùn)行結(jié)果:
jsonStr: [{"age":18,"sex":"man1","userName":"AISMALL1"},{"age":19,"sex":"man2","userName":"AISMALL2"}]
{"sex":"man1","userName":"AISMALL1","age":18}
{"sex":"man2","userName":"AISMALL2","age":19}
4.7.json數(shù)組轉(zhuǎn)List<實(shí)體類>
public class test01 {
public static void main(String[] args) {
// json字符串?dāng)?shù)組
String jsonStr = "[{\"age\":18,\"sex\":\"man1\",\"userName\":\"AISMALL1\"},{\"age\":19,\"sex\":\"man2\",\"userName\":\"AISMALL2\"}]";
System.out.println("jsonStr: " + jsonStr);
// json字符串轉(zhuǎn)換為json數(shù)組
JSONArray jsonArray= JSONArray.parseArray(jsonStr);
List<PersonInfoDto> personInfoDtoList = jsonArray.toJavaList(PersonInfoDto.class);
for (PersonInfoDto personInfoDto:personInfoDtoList) {
System.out.println("personInfoDto: " + personInfoDto);
}
}
}
運(yùn)行結(jié)果:
jsonStr: [{"age":18,"sex":"man1","userName":"AISMALL1"},{"age":19,"sex":"man2","userName":"AISMALL2"}]
personInfoDto: PersonInfoDto{bornTime=null, userName='AISMALL1', sex='man1', age=18}
personInfoDto: PersonInfoDto{bornTime=null, userName='AISMALL2', sex='man2', age=19}
05.josnObject操作的一些小技巧
JSONObject如下:
{
"test": "test",
"Result": [
{
"Result1": "Result1",
"Detail1": "Detail1"
},
{
"Result2": "Result2",
"Detail2": "Detail2"
},
{
"Result3": "Result3",
"Detail3": "Detail3"
}
]
}
5.1.JSONObject中的數(shù)組提取為JSONArray
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"test\":\"test\",\"Result\":[{\"Result1\":\"Result1\",\"Detail1\":\"Detail1\"},{\"Result2\":\"Result2\",\"Detail2\":\"Detail2\"},{\"Result3\":\"Result3\",\"Detail3\":\"Detail3\"}]}";
// json字符串轉(zhuǎn)換為jsonObject
JSONObject jSONObject = JSONObject.parseObject(jsonStr);
// 獲取里面的Json字符串?dāng)?shù)組
JSONArray jsonArray = jSONObject.getJSONArray("Result");
// 轉(zhuǎn)換成Json字符串?dāng)?shù)組之后,就可以遍歷了,字符串是無法遍歷的
for (Object jsonStr2:jsonArray) {
System.out.println(jsonStr2);
}
}
}
運(yùn)行結(jié)果
[{"Detail1":"Detail1","Result1":"Result1"},{"Detail2":"Detail2","Result2":"Result2"},{"Detail3":"Detail3","Result3":"Result3"}]
5.2.JSONObject獲取value
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"test\":\"test\",\"Result\":[{\"Result1\":\"Result1\",\"Detail1\":\"Detail1\"},{\"Result2\":\"Result2\",\"Detail2\":\"Detail2\"},{\"Result3\":\"Result3\",\"Detail3\":\"Detail3\"}]}";
// json字符串轉(zhuǎn)換為jsonObject
JSONObject jSONObject = JSONObject.parseObject(jsonStr);
// 返回值為String類型
String testStr = jSONObject.getString("test");
System.out.println("testStr: " + testStr);
// 返回值為Object類型
Object testObject = jSONObject.get("Result");
System.out.println("testObject: " + testObject);
}
}
運(yùn)行結(jié)果:文章來源:http://www.zghlxwxcb.cn/news/detail-492493.html
testStr: test
testObject: [{"Detail1":"Detail1","Result1":"Result1"},{"Detail2":"Detail2","Result2":"Result2"},{"Detail3":"Detail3","Result3":"Result3"}]
06.總結(jié)
更多方法可以去查看JSONArray
,JSONObject
的源碼。文章來源地址http://www.zghlxwxcb.cn/news/detail-492493.html
到了這里,關(guān)于將json字符串與實(shí)體類互相轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!