json对象转换为实体对象案例:JSONObject,JSONArray之alibaba.fastjson和net.sf.json的不同用法

本文详细介绍如何使用alibaba.fastjson和net.sf.json两个库将JSON对象转换为Java实体对象。通过示例代码展示了如何解析JSON字符串,判断其类型并转换为对应的实体类,适用于后端开发人员快速理解并应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.用alibaba.fastjson将json对象toJavaObject转换为实体对象

技巧:用json在线解析来确定解析为JSONObject还是JSONArray,

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.google.gson.JsonObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestJSON {
    public static void main(String[] args) {
        String jsonString="{\"data\":{\"array1\":[{\"name\":\"aaa\",\"sex\":\"nan\"},{\"name\":\"bbb\",\"sex\":\"nv\"}]}}";
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        JSONObject data = (JSONObject)jsonObject.get("data");
        JSONArray hx = data.getJSONArray("array1");
        for (Object obj:hx){
            JSONObject jsonObject1 = JSONObject.parseObject((String) obj.toString());
            HX hx1 = jsonObject1.toJavaObject(HX.class);
            log.info(hx1.getName());
        }
    }
}
class HX{
    private String name;
    private String sex;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}

 2.用net.sf.json将json对象toBean转换为实体对象

注意:1. net.sf.json的toBean要和@Data一起使用。

           2当有com.alibaba.fastjson.JSONObject时,类在实例化需用net.sf.json.JSONObject jsonBean =……

@Data
public class Ren {
    private String name;
    private String sex;
}
import com.google.gson.JsonObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
public class TestJSON {
    public static void main(String[] args) {
        String jsonString="{\"data\":{\"array1\":[{\"name\":\"aaa\",\"sex\":\"nan\"},{\"name\":\"bbb\",\"sex\":\"nv\"}]}}";
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        JSONObject data = (JSONObject)jsonObject.get("data");
        net.sf.json.JSONArray array1 = net.sf.json.JSONArray.fromObject(data.get("array1"));
        System.out.println(array1);
        for (Object obj : array1) {
            net.sf.json.JSONObject jsonBean = net.sf.json.JSONObject.fromObject(obj);
            Ren ren = (Ren)net.sf.json.JSONObject.toBean(jsonBean, Ren.class);
            System.out.println(ren.getName());
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值