简体   繁体   English

如何使用 Java 将字符串和整数写入 JSON 数组?

[英]How do I write a string and integer into a JSON Array with Java?

I'm trying to create the following results in a JSON file:我正在尝试在 JSON 文件中创建以下结果:

  "numbers": [
    {
        "small": 2,
        "large": 5,
        "type": "single"
    },
    {
        "small": 10,
        "large": 50,
        "type": "double"
    }]

I can't seem to figure out how to use JSON Simple to make this happen (coding in Java).我似乎无法弄清楚如何使用 JSON Simple 来实现这一点(用 Java 编码)。 When I use:当我使用:

JSONObject obj = new JSONObject();
obj.put("small", 2);

it doesn't add it to the array.它不会将它添加到数组中。 When I create an array:当我创建一个数组时:

JSONArray nums = new JSONArray();
nums.add("small", 2)

it doesn't work because add() won't take two parameters.它不起作用,因为 add() 不会接受两个参数。

Please help!请帮忙!

[
    {

That means an array ( [ ] ) of object ( { } ).这意味着对象( { } ) 的数组( [ ] )。

So:所以:

JSONObject obj1 = new JSONObject();
obj1.put("small", 2);
obj1.put("large", 5);
obj1.put("type", "single");

JSONObject obj2 = new JSONObject();
obj2.put("small", 10);
obj2.put("large", 50);
obj2.put("type", "double");

JSONArray nums = new JSONArray();
nums.add(obj1);
nums.add(obj2);

You have a top level object, which contains one field named "numbers", which is an array of objects, each of which contains three fields.您有一个顶级对象,其中包含一个名为“numbers”的字段,它是一个对象数组,每个对象包含三个字段。

So it's likely something like:所以它可能是这样的:

JSONobject top = new JSONobject();
JSONarray arr = new JSONarray();
top.put("numbers", arr);

then for each element in the array然后对于数组中的每个元素

JSONobject obj1 - new JSONobject();
obj1.put("small", 2);
obj1.put("large", 4);
arr.add(obj1);

etc.等等。

I'm not familiar with that particular API but the details depend only on JSON.我不熟悉那个特定的 API,但细节只取决于 JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM