gson

本文详细介绍了如何使用Google的Gson库进行JSON序列化和反序列化操作,包括单个对象、字符串数组和对象数组的处理。通过具体示例展示了如何将Java对象转换为JSON字符串,以及如何从JSON字符串中解析出Java对象。

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

参考:
https://github.com/google/gson
https://google.github.io/gson/apidocs/com/google/gson/Gson.html

编译环境配置参考:
https://search.maven.org/artifact/com.google.code.gson/gson/2.8.5/jar

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;

public class Main {
    static public class MyType {
        String name;
        int id;

        MyType(String name, int id) {
            this.name = name;
            this.id = id;
        }
    }

    public static void SingleObjectTest() {
        Gson gson = new Gson(); // Or use new GsonBuilder().create();
        MyType target = new MyType("harryhare",1234);
        String json = gson.toJson(target); // serializes target to Json
        System.out.println(json);
        MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
        System.out.println(target2.name);
        System.out.println(target2.id);
    }

    public static void ArrayStringTest() {
        Type listType = new TypeToken<List<String>>() {
        }.getType();
        List<String> target = new LinkedList<>();
        target.add("blah");

        Gson gson = new Gson();
        String json = gson.toJson(target, listType);
        System.out.println(json);
        List<String> target2 = gson.fromJson(json, listType);
        System.out.println(target2.get(0));
    }

    public static void ArrayObjectTest() {
        Type listType = new TypeToken<List<MyType>>() {
        }.getType();
        List<MyType> target = new LinkedList<>();
        target.add(new MyType("harryhare",1234));

        Gson gson = new Gson();
        String json = gson.toJson(target, listType);
        System.out.println(json);
        List<MyType> target2 = gson.fromJson(json, listType);
        System.out.println(target2.get(0).name);
        System.out.println(target2.get(0).id);
    }

    public static void main(String[] args) {
        SingleObjectTest();
        ArrayStringTest();
        ArrayObjectTest();
    }
}

{"name":"harryhare","id":1234}
harryhare
1234
["blah"]
blah
[{"name":"harryhare","id":1234}]
harryhare
1234
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值