英文:
How do I write a string and integer into a JSON Array with Java?
问题
"numbers": [
{
"small": 2,
"large": 5,
"type": "single"
},
{
"small": 10,
"large": 50,
"type": "double"
}
]
在使用 JSON Simple 进行操作时,你可以参考以下代码:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonCreationExample {
public static void main(String[] args) {
JSONArray numbersArray = new JSONArray();
JSONObject number1 = new JSONObject();
number1.put("small", 2);
number1.put("large", 5);
number1.put("type", "single");
numbersArray.add(number1);
JSONObject number2 = new JSONObject();
number2.put("small", 10);
number2.put("large", 50);
number2.put("type", "double");
numbersArray.add(number2);
JSONObject result = new JSONObject();
result.put("numbers", numbersArray);
System.out.println(result.toJSONString());
}
}
以上示例代码会创建一个符合你需求的 JSON 结构,并使用 JSON Simple 进行操作。
英文:
I'm trying to create the following results in a JSON file:
"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). 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.
Please help!
答案1
得分: 1
[
{
这表示一个数组 ([ ]
) 包含对象 ({ }
)。
所以:
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);
英文:
[
{
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);
答案2
得分: 0
你有一个顶级对象,其中包含一个名为"numbers"的字段,它是一个包含三个字段的对象数组。
所以可能是这样的:
JSONobject top = new JSONobject();
JSONarray arr = new JSONarray();
top.put("numbers", arr);
然后对数组中的每个元素进行操作:
JSONobject obj1 = new JSONobject();
obj1.put("small", 2);
obj1.put("large", 4);
arr.add(obj1);
等等。
我对这个特定的API不太熟悉,但细节取决于JSON。
英文:
You have a top level object, which contains one field named "numbers", which is an array of objects, each of which contains three fields.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论