Java-多个GSON? [英] Java - Multiple GSON?

查看:77
本文介绍了Java-多个GSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,我正在创建一个使用JSON来保存日期的应用程序.我使用GSON作为我的JSON处理器".

Ok i am creating an application that used JSON to save date. I used GSON as my JSON "processor".

是的,我知道如何使用Gson.我遵循网上教程.问题是,网络上的教程仅保存一个" json数据.我的意思是,例如,

Yes i know how to use Gson. I follow the tutorial on web. The problem is, the tutorial on web and only save "one" json data. I mean, for example,

{
    "Data1": {
      "name": "Data1",
      "info": "ABCDEFG"
    }
}

因此,在用户保存了Data1之后,他们想要这样保存Data2,Data3等

So, after user saved Data1, they want to save Data2, Data3, etc like this

{
    "Data1": {
      "name": "Data1",
      "info": "ABCDEFG"
    },
    "Data2": {
      "name": "Data2",
      "info": "ABCDEFGHIJ"
    }
}

但是,如果用户要保存100多个数据,我必须进行100个课程吗?下面是我的代码.

But if user want to save 100+ data do i have to make 100 classes? Below are my code.

JSONTest.class

JSONTest.class

public class JSONTest
{
    private static Gson gson;
    private static File file;
    private static JSONTest instance;
    private static Bean bean;
    private static Map<String, String> data = new HashMap();

    public static void main(String[] args)
    {
        bean = new Bean();
        File file = new File("C://test-json.json");
        GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        gson = builder.create();

        data.put("name", "data1");
        data.put("info", "abcde");
        bean.setData(data);


        String jsonString = gson.toJson(bean);

        try
        {
            FileWriter fw = new FileWriter(file);
            fw.write(jsonString);
            fw.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

Bean.class

Bean.class

public class Bean
{
    private Map<String, String> data;

    public Map<String, String> getData()
    {
        return data;
    }

    public void setData(Map<String, String> properties)
    {
        this.data = properties;
    }
}

结果就是这样

{
  "data": {
    "name": "data1",
    "info": "abcde"
  }
}

好,现在我更改值(意味着我要添加新数据

ok now i change the value(mean that i want to add new data

data.put("name", "data2");
data.put("info", "abcdef");
bean.setData(data);

结果是这个

{
  "data": {
    "name": "data2",
    "info": "abcdef"
  }
}

但是我想要这样的结果

{
    "data1": {
      "name": "data1",
      "info": "abcde"
    },
    "data2": {
      "name": "data2",
      "info": "abcdef"
    }
}

所以我的问题是,我该怎么办?如果用户要保存100多个数据,我必须创建100多个类或元素吗?而且,如何添加"selectedData: "data1"",以便我的json加载器仅加载1个数据?

So my question is, how can i do that?If user want to save 100+ data do i have to make 100+classes or elements? And also, how to add "selectedData: "data1"" so my json loader so load 1 data only?

推荐答案

在使用JSON解析器/生成器之前,您必须了解所使用的JSON.

You have to understand the JSON you are using before you use a JSON parser/generator.

{
    "Data1": {
      "name": "Data1",
      "info": "ABCDEFG"
    }
}

是一个JSON对象,其中包含名称为Data1的JSON对象.

is a JSON object containing a JSON object with the name Data1.

{
    "Data1": {
      "name": "Data1",
      "info": "ABCDEFG"
    },
    "Data2": {
      "name": "Data2",
      "info": "ABCDEFGHIJ"
    }
}

是一个JSON对象,其中包含两个名为Data1Data2的JSON对象.

is a JSON object containing two JSON objects named Data1 and Data2.

一个简单的工作示例是

public static void main(String[] args) throws Exception {
    String json =   "{              \"Data1\": {                  \"name\": \"Data1\",                \"info\": \"ABCDEFG\"             },              \"Data2\": {                  \"name\": \"Data2\",                \"info\": \"ABCDEFGHIJ\"              }           }";
    Gson gson = new Gson();
    Map<String, CustomBean> objects = gson.fromJson(json, new TypeToken<Map<String, CustomBean>>() {}.getType());
    System.out.println(objects);
}

其中CustomBean

public class CustomBean {

    private String name;
    private String info;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public String toString() {
        return "[name = " + name + ", info = " + info + "]";
    }

}

上面的照片

{Data1=[name = Data1, info = ABCDEFG], Data2=[name = Data2, info = ABCDEFGHIJ]}

由于两个嵌套对象都相同,所以您可以告诉Gson将它们反序列化为Map,其中JSON对象的名称是键,而对象本身是值.

Since both nested objects are the same, you can tell Gson to deserialize them into a Map where the name of the JSON object is the key and the object itself is the value.

JSON格式具有可以映射到Java类型的非常具体的类型.您必须使用相应的类型.例如,您将List用于JSON数组.

The JSON format has very specific types that can map to Java types. You have to use the corresponding types. For example, you would use a List for a JSON array.

既然您已对其进行编辑,让我们回到您的问题

Let's go back to your question now that you've edited it

所以我的问题是,我该怎么办?如果用户要保存100多个数据,该怎么办? 我必须制作100多个类或元素?而且,如何添加 "selectedData:" data1"所以我的json加载程序只加载1个数据?

So my question is, how can i do that?If user want to save 100+ data do i have to make 100+classes or elements? And also, how to add "selectedData: "data1"" so my json loader so load 1 data only?

在您给出的示例中,对我来说,您似乎误解了Gson的工作原理.

With the example you've given, it looks to me like you misunderstand how Gson works.

Gson尝试将您的对象序列化为JSON对象.像

Gson tries to serialize your object to a JSON object. An object of a simple class like

public class Bean {
    private String name = "some value";
    private String info = "some other value";
}

很好地映射到以下JSON对象

maps nicely to the following JSON object

{
    "name" : "some value",
    "info" : "some other value"
}

java类Map是一个特殊的类,可以很好地映射到JSON.键用作JSON对象的名称,值用作JSON对象的值,可以是数字,字符串,JSON数组或另一个JSON对象.因此,以下代码段中的Map对象

The java class Map is a special class that maps nicely to JSON. The key is used as the name of the JSON object and the value is used as the value of the JSON object, be it a number, String, JSON array, or another JSON object. So the Map object in the following snippet

Map<String, Bean> map = new HashMap<>();
map.put("data1", new Bean());

由Gson序列化的将提供以下JSON

serialized by Gson would give the following JSON

{
    "data1": {
      "name": "some value",
      "info": "some other value"
    }
}

因为键是String data1,并且值是另一个JSON对象,该对象已如我上面显示的那样进行了序列化.

Because the key is the String data1 and the value is another JSON object which is serialized as I showed above.

所以我的问题是,我该怎么办?如果用户要保存100多个数据,该怎么办? 我必须制作100多个类或元素?

So my question is, how can i do that?If user want to save 100+ data do i have to make 100+classes or elements?

上面已经清楚您需要做什么.

It should be clear with the above what you need to do.

而且,如何添加"selectedData:"data1"",所以我的json加载器也是如此 仅加载1个数据?

And also, how to add "selectedData: "data1"" so my json loader so load 1 data only?

请阐明您的意思.您不能仅加载JSON的子集. Gson将全部加载,您可以从中提取名为data1的JSON对象.

Please clarify what you mean. You can't load only a subset of the JSON. Gson will load all of it, you can extract the JSON object named data1 from that.

这篇关于Java-多个GSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆