I have 2 arrays with Strings.
我有2个带字符串的数组。
String [] keys = {"key1", "key2",....}
String [] values = {"value1", "value2",....}
Their size is not known, but they have the same size.
它们的大小尚不清楚,但它们的大小相同。
I want to generate a Json object out of them, such that:
我想从中生成一个Json对象,这样:
{
"key1":"value1",
"key2":"value2",
...
}
What will be a good practice for that?
对此有什么好的做法?
3 个解决方案
#1
2
You can iterate over the arrays, taking each key, value
pair, and add them to a JSON object.
您可以迭代数组,获取每个键,值对,并将它们添加到JSON对象。
gson:
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < keys.length; i ++) {
jsonObject.addProperty(keys[i], values[i]);
}
Jackson:
ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
for (int i = 0; i < keys.length; i ++) {
jsonObject.put(keys[i], values[i]);
}
#2
1
As an options you can create a Map
and just serialize it using ObjectMapper
from Jackson library :
作为选项,您可以创建一个Map,并使用Jackson库中的ObjectMapper对其进行序列化:
Map<String, String> map = new HashMap<>();
for (int i = 0; i < keys.length; ++i) {
map.put(keys[i], values[i]);
}
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(map);
#3
0
I would say put them into a Map, then convert into JSON using something like Gson.
我会说把它们放到Map中,然后使用像Gson这样的东西转换成JSON。
public static void main(String[] args) {
String[] keys = {"key1", "key2"};
String[] values = {"value1", "value2"};
Map<String, String> map = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i]);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(map));
}
#1
2
You can iterate over the arrays, taking each key, value
pair, and add them to a JSON object.
您可以迭代数组,获取每个键,值对,并将它们添加到JSON对象。
gson:
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < keys.length; i ++) {
jsonObject.addProperty(keys[i], values[i]);
}
Jackson:
ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
for (int i = 0; i < keys.length; i ++) {
jsonObject.put(keys[i], values[i]);
}
#2
1
As an options you can create a Map
and just serialize it using ObjectMapper
from Jackson library :
作为选项,您可以创建一个Map,并使用Jackson库中的ObjectMapper对其进行序列化:
Map<String, String> map = new HashMap<>();
for (int i = 0; i < keys.length; ++i) {
map.put(keys[i], values[i]);
}
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(map);
#3
0
I would say put them into a Map, then convert into JSON using something like Gson.
我会说把它们放到Map中,然后使用像Gson这样的东西转换成JSON。
public static void main(String[] args) {
String[] keys = {"key1", "key2"};
String[] values = {"value1", "value2"};
Map<String, String> map = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i]);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(map));
}