Tasso Tasso - 4 months ago 22
Java Question

Resteasy: how to save JSON with not fixed keys

I use reasteasy to call REST API.

My problem is that the JSON from the REST API has dynamic values. For example:

"labels": {
"kubernetes.io/hostname": "192.168.200.176",
"node": "master"
}


Where "node" and "kubernetes.io/hostname" could be any string.

I've tried to map "labels" into a
Map <String, String>
object. The variable is correctly created but it remains empty. How can I generate a dictionary with for example
{"kubernetes.io/hostname": "192.168.200.176", "node": "master"}
?`

Answer

If you're fine with just creating a Map instead of a specific domain object, you can simply parse the JSON yourself to get a list of the keys and create the Map yourself.

Here's an example using org.json:

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

public class Scratch {
    public static void main(String[] args) throws Exception {
        String json = "{ \"labels\": { \"kubernetes.io/hostname\": \"192.168.200.176\", \"node\": \"master\" } }";
        Map<String, String> library = new HashMap<>();

        // parse the input string
        JSONObject labels = new JSONObject(json).getJSONObject("labels");

        // iterate over keys and insert into Map
        for (String key : labels.keySet()) {
            library.put(key, labels.getString(key));
        }

        System.out.println(library);
        // {kubernetes.io/hostname=192.168.200.176, node=master}
    }
}


You can also do more-or-less the same thing with Gson, by simply wrapping the Map in a container class, and letting it do the actual deserialization:

import java.util.Map;
import com.google.gson.Gson;

public class Scratch {
    public static void main(String[] args) throws Exception {
        String json = "{ \"labels\": { \"kubernetes.io/hostname\": \"192.168.200.176\", \"node\": \"master\" } }";

        Library library = new Gson().fromJson(json, Library.class);
        System.out.println(library.labels);
        // {kubernetes.io/hostname=192.168.200.176, node=master}
    }
}

class Library {
    Map<String, String> labels;
}


In both cases, notice that you have to get the data from inside the "labels" field of the JSON, not the top level.

Comments