JSON格式及FastJson使用详解

本文详细介绍了FastJson库在Java中如何将JSON字符串转换为JSONObject,进一步解析并获取其中的数据,包括JSONObject到JSON字符串的转换,以及JSON字符串与JavaBean之间的互转。文中给出了具体示例,包括复杂JSON格式到JavaBean对象的转换方法,并提供了不同方式的转换代码示例。
摘要由CSDN通过智能技术生成

@Test

public void JSONStringTOJSONObject(){

JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);

// 获取简单对象

String teacherName = jsonObject.getString(“teacherName”);

Integer teacherAge = jsonObject.getInteger(“teacherAge”);

System.out.println("teacherName: " + teacherName + ",teacherAge " + teacherAge);

// 获取JSONObject对象

JSONObject course = jsonObject.getJSONObject(“course”);

// 获取JSONObject中的数据

String courseName = course.getString(“courseName”);

Integer code = course.getInteger(“code”);

System.out.println("courseName: " + courseName + " code: " + code);

// 获取JSONArray对象

JSONArray students = jsonObject.getJSONArray(“students”);

// 获取JSONArray的中的数据

Iterator iterator = students.iterator();

while (iterator.hasNext()){

JSONObject jsonObject1 = (JSONObject) iterator.next();

System.out.println("studentName: " + jsonObject1.getString(“studentName”) + ",StudentAge: "

  • jsonObject1.getInteger(“studentAge”));

}

}

3.6 复杂JSONObject—》json字符串


用JSON.toJSONString()方法即可将复杂JSONObject转化为JSON字符串

/**

  • 复杂JSONObject到json字符串的转换

*/

@Test

public void JSONObjectTOJSON(){

JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);

String s = JSON.toJSONString(jsonObject);

System.out.println(s);

}

3.7 json字符串—》JavaBean


定义JavaBean类

package com.fastjson;

public class Student {

private String studentName;

private int studentAge;

public Student() {

}

public Student(String studentName, int studentAge) {

this.studentName = studentName;

this.studentAge = studentAge;

}

public String getStudentName() {

return studentName;

}

public void setStudentName(String studentName) {

this.studentName = studentName;

}

public int getStudentAge() {

return studentAge;

}

public void setStudentAge(int studentAge) {

this.studentAge = studentAge;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值