Java 在 JSON 中创建键值对字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16306271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:14:42  来源:igfitidea点击:

Create key-value pairs string in JSON

javajson

提问by sashi

I'm new to JSON. I'm trying to create a JSON string in Java (org.json.JSONObject(json.jar)) which resembles like (basically a set of name-value pairs)

我是 JSON 的新手。我正在尝试在 Java (org.json.JSONObject(json.jar)) 中创建一个类似于(基本上是一组名称-值对)的 JSON 字符串

[{
    "name": "cases",
    "value": 23
}, {
    "name": "revenue",
    "value": 34
}, {
    "name": "1D5",
    "value": 56
}, {
    "name": "diag",
    "value": 14
}]

Can anyone help me on how to create this in Java? I want the name and value to be in each so that i can iterate over the collection and then get individual values.

任何人都可以帮助我如何在 Java 中创建它?我希望名称和值都在每个中,以便我可以迭代集合然后获取单独的值。

采纳答案by Brigham

The library is chained, so you can create your object by first creating a json array, then creating the individual objects and adding them one at a time to the array, like so:

该库是链接的,因此您可以通过首先创建一个 json 数组,然后创建单个对象并将它们一次添加到数组中来创建对象,如下所示:

new JSONArray()
    .put(new JSONObject()
            .put("name", "cases")
            .put("value", 23))
    .put(new JSONObject()
            .put("name", "revenue")
            .put("value", 34))
    .put(new JSONObject()
            .put("name", "1D5")
            .put("value", 56))
    .put(new JSONObject()
            .put("name", "diag")
            .put("value", 14))
    .toString();

Once you have the final array, call toStringon it to get the output.

获得最终数组后,调用toString它以获取输出。

回答by Hot Licks

What you've got there is a JSON array containing 4 JSON objects. Each object contains two keys and two values. In Java a JSON "object" is generally represented by some sort of "Map".

你得到的是一个包含 4 个 JSON 对象的 JSON 数组。每个对象包含两个键和两个值。在 Java 中,JSON“对象”通常由某种“地图”表示。

回答by Mihai B.

Try to use gson if you have to work a lot with JSON in java. Gsonis a Java library that can be used to convert Java Objects into JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

如果您必须在 Java 中大量使用 JSON,请尝试使用 gson。 Gson是一个 Java 库,可用于将 Java 对象转换为 JSON 表示。它还可用于将 JSON 字符串转换为等效的 Java 对象。

Here is a small example:

这是一个小例子:

Gson gson = new Gson();
gson.toJson(1);            ==> prints 1
gson.toJson("abcd");       ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values);       ==> prints [1]