简体   繁体   中英

How to convert 2 Java String arrays of keys & values into a json object

I have 2 arrays with Strings.

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:

{
"key1":"value1",
"key2":"value2",
...
} 

What will be a good practice for that?

You can iterate over the arrays, taking each key, value pair, and add them to a JSON object.

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]);
}

As an options you can create a Map and just serialize it using ObjectMapper from Jackson library :

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);

I would say put them into a Map, then convert into JSON using something like Gson.

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));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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