以JSON纯文本插入String数组

时间:2021-07-10 21:21:45

I've created some JSON strings in Java but I don't know how to insert string array.

我用Java创建了一些JSON字符串,但我不知道如何插入字符串数组。

For example, I've want to add string the format is:

例如,我想添加字符串格式为:

String aux1 = "{ \"key\" : \"value\"};

But if i want to add as value: new String[] {"string1", "string2"};

但是如果我想添加值:new String [] {“string1”,“string2”};

How I can represent a string array in text-plain format??

我怎样才能以文本格式表示字符串数组?

Thanks

谢谢

3 个解决方案

#1


0  

Use the JSONObject class :

使用JSONObject类:

JSONObject object = new JsonObject();
object.put("key1", "value1");
object.put("key2", "value2");
String jsonString = object.toString(); //This will create the corresponding JSON-formatted string

#2


0  

You can use something like this:

你可以使用这样的东西:

String[] strArray = new String[] {"string1", "string2"};

JSONObject jo = new JSONObject();
jo.put("key", Arrays.asList(strArray));

Output would be:

输出将是:

{"key":["string1","string2"]}

#3


0  

String[] strArray = new String[] {"string1", "string2"};
String str1 = Arrays.toString(strArray);
JSONObject jobj = new JSONObject();
jobj.put("yourstringKey",str1);

you can do above way only if your strArray size is more(supose greater than 10.) But if your array is small.then use following way.

只有当你的strArray大小更大(大于10)时你才可以做到这一点。但是如果你的数组很小,那么使用下面的方法。

JSONObject jobj1=new JSONObject();
jobj1.put("key1","value1");
jobj1.put("key2","value2");
JSONObject jobj=new JSONObject();
jobj.put("mystring",jobj1.toStirng());

#1


0  

Use the JSONObject class :

使用JSONObject类:

JSONObject object = new JsonObject();
object.put("key1", "value1");
object.put("key2", "value2");
String jsonString = object.toString(); //This will create the corresponding JSON-formatted string

#2


0  

You can use something like this:

你可以使用这样的东西:

String[] strArray = new String[] {"string1", "string2"};

JSONObject jo = new JSONObject();
jo.put("key", Arrays.asList(strArray));

Output would be:

输出将是:

{"key":["string1","string2"]}

#3


0  

String[] strArray = new String[] {"string1", "string2"};
String str1 = Arrays.toString(strArray);
JSONObject jobj = new JSONObject();
jobj.put("yourstringKey",str1);

you can do above way only if your strArray size is more(supose greater than 10.) But if your array is small.then use following way.

只有当你的strArray大小更大(大于10)时你才可以做到这一点。但是如果你的数组很小,那么使用下面的方法。

JSONObject jobj1=new JSONObject();
jobj1.put("key1","value1");
jobj1.put("key2","value2");
JSONObject jobj=new JSONObject();
jobj.put("mystring",jobj1.toStirng());