Java 创建没有键值的 JsonArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20348438/
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-13 01:14:12  来源:igfitidea点击:

Create JsonArray without key value

javajsongson

提问by AkiraYamaokaNC

Please help me create jSonArray without keys. It should looks like:

请帮我创建没有键的 jSonArray。它应该看起来像:

"main" : ["one", "two", "three"]

I have tried it with empty key value:

我用空键值尝试过:

private String generate(String value) {

    Gson gson = new Gson();
    JsonArray jsonArray = new JsonArray();
    JsonObject jsonObject = new JsonObject();

    jsonObject.addProperty("", value);
    jsonArray.add(jsonObject);

    return gson.toJson(jsonArray);
}

Result looks bad..

结果看起来很糟糕..

"main": "[
  {\"\":\
  "myString value\"}
]"

采纳答案by lummycoder

JsonObject obj = new JsonObject();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("one"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
obj.add("main", array);

回答by Konstantin Yovkov

You can do something like:

您可以执行以下操作:

Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("one"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));

JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);;

System.out.println(gson.toJson(jsonObject));

which outputs:

输出:

{"main":["one","two","three"]}

回答by Cirou

What you are trying to do is just to fill an array with primitive variables, to achieve that you have to change your code like this:

您要做的只是用原始变量填充数组,以实现您必须像这样更改代码:

private String generate(String value) {

    Gson gson = new Gson();

    JsonArray jsonArray = new JsonArray();
    jsonArray.add(new JsonPrimitive(value));

    return gson.toJson(jsonArray);
}

回答by Vishal Ranapariya

Sample Code

示例代码

JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
obj.put("", list);

You can use this to put an array without key.

您可以使用它来放置没有键的数组。