如何使用 java 提供以下 json 输出

发布于 2024-09-29 04:29:50 字数 574 浏览 5 评论 0原文

我尝试使用 java net.sf.json 库生成以下 json 输出,但没有成功。

[ { “数据”: [ [ 1、 1、 “文本” ], [ 2、 2、 “文本” ], [ 3、 0, “文本” ], [ 5、 2、 “文本” ] ], “label”:“第一系列” } ]

我在这些论坛上读到 Gson 是我未来最好的选择。任何人都可以提供如何使用 Gson 或其他合适的基于 java 的库生成此 json 的示例。

提前致谢

I am trying to generate the following json output using the java net.sf.json libs but have been unsuccessful.

[
{
"data": [
[
1,
1,
"Text"
],
[
2,
2,
"Text"
],
[
3,
0,
"Text"
],
[
5,
2,
"Text"
]
],
"label": "First Series"
}
]

I have read on these forums Gson is my best bet going forward. Can anyone provide an example of how to generate this json using Gson or another suitable java based library.

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清醇 2024-10-06 04:29:50

我喜欢这个
http://www.json.org/javadoc/org/json/JSONObject.html 来自 http://json.org/java/

和 JSONArray。

与这两个对象:

JSONArray inner = new JSONArray()
inner.add(1);inner.add("text");
JSONObject outer = new JSONObject();
outer.put("data",inner);
outer.put("label", "stuff");

String out = outer.toString()

i like this
http://www.json.org/javadoc/org/json/JSONObject.html from http://json.org/java/

and JSONArray.

with those 2 objects:

JSONArray inner = new JSONArray()
inner.add(1);inner.add("text");
JSONObject outer = new JSONObject();
outer.put("data",inner);
outer.put("label", "stuff");

String out = outer.toString()
暮年慕年 2024-10-06 04:29:50

Gson

Gson 是一个 Java 库,可用于将 Java 对象转换为其 JSON 表示形式。它还可用于将 JSON 字符串转换为等效的 Java 对象。 Gson 可以处理任意 Java 对象,包括您没有源代码的现有对象。

有一些开源项目可以将 Java 对象转换为 JSON。然而,它们中的大多数都要求您在类中放置 Java 注释,如果您无权访问源代码,则无法执行此操作。大多数也不完全支持 Java 泛型的使用。 Gson 认为这两个都是非常重要的设计目标。

import com.google.gson.Gson;
 
class Person {
  private int age = 10;
  private String name = "jigar";
}
 
Person obj = new Person();
Gson gson = new Gson();
String json = gson.toJson(obj);

http://json.org/java/

import org.json.JSONObject;

...
...

JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");

...

String output = json.toString();  

Gson

Gson is a Java library that can be used to convert Java Objects into its JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

import com.google.gson.Gson;
 
class Person {
  private int age = 10;
  private String name = "jigar";
}
 
Person obj = new Person();
Gson gson = new Gson();
String json = gson.toJson(obj);

http://json.org/java/

import org.json.JSONObject;

...
...

JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");

...

String output = json.toString();  
毅然前行 2024-10-06 04:29:50

使用像这样的 Java 对象,这很容易:

public class GsonTest {
  private List<DataItem> data;
  private String label;

  public GsonTest() {} // for Gson

  public GsonTest(List<DataItem> data, String label) {
    this.data = data;
    this.label = label;
  }
  // ...
}

public class DataItem {
  private int val1;
  private int val2;
  private String text;

  public DataItem() {} // for Gson

  public DataItem(int val1, int val2, String text) {
    this.val1 = val1;
    this.val2 = val2;
    this.text = text;
  }
  // ...
}

由于您的 JSON 格式对每个数据项使用数组而不是对象(根据您的示例,对象会更有意义),您需要添加一个自定义处理程序来序列化和反序列化 < code>DataItem 与 JSON 数组之间的转换。

public class DataItemConverter implements JsonDeserializer<DataItem>,
    JsonSerializer<DataItem> {

  public DataItem deserialize(JsonElement json, Type typeOfT, 
      JsonDeserializationContext context) throws JsonParseException {
    JsonArray array = json.getAsJsonArray();
    int val1 = array.get(0).getAsInt();
    int val2 = array.get(1).getAsInt();
    String text = array.get(2).getAsString();
    return new DataItem(val1, val2, text);
  }

  public JsonElement serialize(DataItem src, Type typeOfSrc, 
      JsonSerializationContext context) {
    JsonArray array = new JsonArray();
    array.add(new JsonPrimitive(src.val1));
    array.add(new JsonPrimitive(src.val2));
    array.add(new JsonPrimitive(src.text));
    return array;
  }
}

然后,您只需在创建 Gson 实例时注册此转换器即可开始!由于我们的 DataItem 转换器也可以处理反序列化,因此您也可以将生成的 JSON 反序列化为 List

public static void testSerialization() {
  List<DataItem> data = new ArrayList<DataItem>();
  data.add(new DataItem(1, 1, "Text"));
  data.add(new DataItem(2, 2, "Text"));
  data.add(new DataItem(3, 0, "Text"));
  data.add(new DataItem(5, 2, "Text"));

  GsonTest test = new GsonTest(data, "First Series");
  List<GsonTest> list = new ArrayList<GsonTest>();
  list.add(test);
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(DataItem.class, new DataItemConverter())
      .create();
  System.out.println(gson.toJson(list));
}

This is easy enough using a Java object like this:

public class GsonTest {
  private List<DataItem> data;
  private String label;

  public GsonTest() {} // for Gson

  public GsonTest(List<DataItem> data, String label) {
    this.data = data;
    this.label = label;
  }
  // ...
}

public class DataItem {
  private int val1;
  private int val2;
  private String text;

  public DataItem() {} // for Gson

  public DataItem(int val1, int val2, String text) {
    this.val1 = val1;
    this.val2 = val2;
    this.text = text;
  }
  // ...
}

Since your JSON format uses an array rather than an object for each data item (an object would make more sense based on your sample) you need to add a custom handler for serializing and deserializing DataItems to and from JSON arrays.

public class DataItemConverter implements JsonDeserializer<DataItem>,
    JsonSerializer<DataItem> {

  public DataItem deserialize(JsonElement json, Type typeOfT, 
      JsonDeserializationContext context) throws JsonParseException {
    JsonArray array = json.getAsJsonArray();
    int val1 = array.get(0).getAsInt();
    int val2 = array.get(1).getAsInt();
    String text = array.get(2).getAsString();
    return new DataItem(val1, val2, text);
  }

  public JsonElement serialize(DataItem src, Type typeOfSrc, 
      JsonSerializationContext context) {
    JsonArray array = new JsonArray();
    array.add(new JsonPrimitive(src.val1));
    array.add(new JsonPrimitive(src.val2));
    array.add(new JsonPrimitive(src.text));
    return array;
  }
}

Then you just need to register this converter when you create your Gson instance and you're good to go! Since our DataItem converter handles deserialization as well, you'll be able to deserialize the generated JSON as a List<GsonTest> as well.

public static void testSerialization() {
  List<DataItem> data = new ArrayList<DataItem>();
  data.add(new DataItem(1, 1, "Text"));
  data.add(new DataItem(2, 2, "Text"));
  data.add(new DataItem(3, 0, "Text"));
  data.add(new DataItem(5, 2, "Text"));

  GsonTest test = new GsonTest(data, "First Series");
  List<GsonTest> list = new ArrayList<GsonTest>();
  list.add(test);
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(DataItem.class, new DataItemConverter())
      .create();
  System.out.println(gson.toJson(list));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文