FastJson中JSON,JSONObject和JSONArray简单使用

文章讲述了在Java项目中通过Fastjson进行对象至JSON字符串和反序列化的实例,以及如何使用NameFilter进行命名格式化。
JSON中提供了常用的对象和json数据间的转换方法。
JSONObject可以看作Map,使用key-value构建json对象。
JSONArray可以看作List,使用List可以简单构造json数组对象。

1.pom.xml中引入依赖
<dependency>
   <groupId>com.alibaba.fastjson2</groupId>
   <artifactId>fastjson2</artifactId>
   <version>2.0.29</version>
</dependency>

2.准备实体类
import com.alibaba.fastjson2.annotation.JSONField;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;

@Slf4j
@Data
public class Person {
    @JSONField(name="AGE", serialize=false)
    private int age;

    @JSONField(name="LAST NAME", ordinal = 2)
    private String lastName;

    @JSONField(name="FIRST NAME", ordinal = 1)
    private String firstName;

    @JSONField(name="DATE OF BIRTH", format="dd/MM/yyyy", ordinal = 3)
    private Date dateOfBirth;

    public Person() {
    }
    public Person(int age, String lastName, String firstName, Date dateOfBirth) {
        this.age = age;
        this.lastName = lastName;
        this.firstName = firstName;
        this.dateOfBirth = dateOfBirth;
    }
}

3.准备测试类
import com.test.fastjson.to.Person;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.filter.NameFilter;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

@Slf4j
class TestTest {
    private List<Person> listOfPersons = new ArrayList<>();

    @BeforeEach
    public void setUp() {
        listOfPersons.add(new Person(15, null,"Doe", new Date()));
        listOfPersons.add(new Person(20, "Janette Doe", "Kobe", new Date()));
    }

    /**
     * convert object to json String.
     */
    @Test
    public void whenJavaList_thanConvertToJsonCorrect() {
        String jsonOutput= JSON.toJSONString(listOfPersons);
        log.info(jsonOutput);
    }

    /**
     * json string to object
     */
    @Test
    public void whenJson_thanConvertToObjectCorrect() {
        Person person = new Person(20, "John", "Doe", new Date());
        String jsonObject = JSON.toJSONString(person);
        Person newPerson = JSON.parseObject(jsonObject, Person.class);

        assertEquals(newPerson.getAge(), 0); // 如果我们设置系列化为 false
        assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName());
    }

    /**
     * how to use JSONObject and JSONArray
     */
    @Test
    public void whenGenerateJson_thanGenerationCorrect() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < 2; i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("AGE", 10);
            jsonObject.put("FULL NAME", "Doe " + i);
            jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
            jsonArray.add(jsonObject);
        }
        String jsonOutput = jsonArray.toJSONString();
        log.info(jsonOutput);
    }

    /**
     * define NameFilter
     */
    @Test
    public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
        NameFilter formatName = new NameFilter() {
            public String process(Object object, String name, Object value) {
                return name.toLowerCase().replace(" ", "_");//FIRST NAME  ---> first_name
            }
        };
        String jsonOutput = JSON.toJSONString(listOfPersons, formatName);
        log.info(jsonOutput);
    }

}

<think>我们被要求提供使用FastJson库将字符串转换为JsonObject(即JsonData)JsonArray的示例代码。 根据引用[2]中的内容,FastJson提供了以下方法: - 将字符串解析为JSONObjectJSON.parseObject(String text) - 将字符串解析为JSONArrayJSON.parseArray(String text) 同时,如果要将字符串解析为特定类型的JavaBean,可以使用: - JSON.parseObject(String text, Class<T> clazz) - 解析为特定类型的List:JSON.parseArray(String text, Class<T> clazz) 但用户的问题中并没有提到具体的JavaBean类型,所以我们将提供基本的使用示例。 示例步骤: 1. 添加FastJson依赖(如果项目中尚未添加) 2. 导入必要的类 3. 示例代码:字符串转JsonObject(即JSONObject) 4. 示例代码:字符串转JsonArray(即JSONArray) 注意:JsonData在FastJson中通常指的是JSONObject(表示一个JSON对象)或JSONArray(表示一个JSON数组),但有时也可能指具体的Java对象。根据上下文,这里我们理解为JSONObjectJSONArray。 假设我们有以下两个字符串: - 表示对象的字符串:`String jsonObjectStr = "{\"name\":\"John\", \"age\":30}";` - 表示数组的字符串:`String jsonArrayStr = "[{\"name\":\"John\", \"age\":30}, {\"name\":\"Jane\", \"age\":25}]";` 我们将使用FastJson的API进行转换。</think>### FastJSON 字符串转 JSONObject JSONArray 示例 以下是使用 FastJSON 库将字符串转换为 JSONObject JSONArray 的完整示例代码: ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class FastJsonExample { public static void main(String[] args) { // 示例1: 字符串转 JSONObject (JsonData) String jsonStr = "{\"name\":\"John\", \"age\":30, \"isStudent\":false}"; // 方法1: 直接解析为 JSONObject JSONObject jsonObject1 = JSON.parseObject(jsonStr); System.out.println("JSONObject 解析结果:"); System.out.println("姓名: " + jsonObject1.getString("name")); System.out.println("年龄: " + jsonObject1.getInteger("age")); System.out.println("是否学生: " + jsonObject1.getBoolean("isStudent")); // 方法2: 先解析为通用对象再转换 Object obj = JSON.parse(jsonStr); if (obj instanceof JSONObject) { JSONObject jsonObject2 = (JSONObject) obj; System.out.println("\n转换结果验证: " + jsonObject2.toJSONString()); } // 示例2: 字符串转 JSONArray String arrayStr = "[{\"id\":1,\"product\":\"Laptop\"}, {\"id\":2,\"product\":\"Phone\"}]"; // 方法1: 直接解析为 JSONArray JSONArray jsonArray1 = JSON.parseArray(arrayStr); System.out.println("\nJSONArray 解析结果:"); for (int i = 0; i < jsonArray1.size(); i++) { JSONObject item = jsonArray1.getJSONObject(i); System.out.println("商品" + (i+1) + ": ID=" + item.getInteger("id") + ", 名称=" + item.getString("product")); } // 方法2: 使用泛型指定元素类型 List<Product> products = JSON.parseArray(arrayStr, Product.class); System.out.println("\n转换为Java对象:"); products.forEach(p -> System.out.println(p)); } // 辅助类 static class Product { private int id; private String product; // Getters/Setters @Override public String toString() { return "Product{id=" + id + ", product='" + product + "'}"; } } } ``` #### 关键方法说明: 1. **字符串转 JSONObject**: ```java // 直接解析 JSONObject obj = JSON.parseObject(jsonString); // 解析为特定类型 MyClass obj = JSON.parseObject(jsonString, MyClass.class); ``` 2. **字符串转 JSONArray**: ```java // 直接解析 JSONArray array = JSON.parseArray(jsonArrayString); // 解析为特定类型列表 List<MyClass> list = JSON.parseArray(jsonArrayString, MyClass.class); ``` 3. **类型转换方法**: ```java jsonObject.getString("key") // 获取字符串值 jsonObject.getInteger("key") // 获取整数值 jsonObject.getBoolean("key") // 获取布尔值 jsonArray.getJSONObject(index) // 获取数组元素 ``` #### 输出结果示例: ``` JSONObject 解析结果: 姓名: John 年龄: 30 是否学生: false 转换结果验证: {"isStudent":false,"name":"John","age":30} JSONArray 解析结果: 商品1: ID=1, 名称=Laptop 商品2: ID=2, 名称=Phone 转换为Java对象: Product{id=1, product='Laptop'} Product{id=2, product='Phone'} ``` #### 依赖配置(Maven): ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> <!-- 使用最新版本 --> </dependency> ``` > **注意**:实际使用时需处理可能的异常 `JSONException`,确保输入字符串是有效的 JSON 格式[^2]。 --- ### 相关问题 1. FastJSON 如何处理嵌套的 JSON 对象数组? 2. 使用 FastJSON 时有哪些常见的安全风险及防范措施? 3. FastJSON 与其他 JSON 库(如 Gson、Jackson)的主要区别是什么? 4. 如何将 JSONObjectJSONArray 转换回 JSON 字符串? 5. FastJSON 是否支持自定义序列化反序列化规则?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值