Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a wrapper from a JSON Object?

Tags:

java

json

gson

I have a JSON object with a wrapper which contains information about the service it came from. Before parsing the object I really care about I would like to take off the wrapper and then just parse the object.

How do I turn this JSON object:

{"object":{"id_object": 1, "description": "Black" }, "origin":"colors"}

Into this:

{"id_object": 1, "description": "Black"}

I am using GSON as JSON parser, but if any other will give me the functionallity, I can change the library.

Thanks in advance.

like image 400
Oso Avatar asked Sep 17 '25 06:09

Oso


2 Answers

Since the whole thing is a blob of json, it doesn't make sense to 'unwrap it.' Just parse the whole thing, and and grab the value of the 'object' key, and go along from there.

like image 131
bmargulies Avatar answered Sep 19 '25 20:09

bmargulies


Super hacky solution:

private class Holder{
    private IdHolder object;
    private String origin;

    public IdHolder getObject() {
        return object;
    }
    public String getOrigin() {
        return origin;
    }

    private class IdHolder{
        private int id_object;
        private String description;
    }
}


    Holder holder = gson.fromJson("{\"object\":{\"id_object\": 1, \"description\": \"Black\" }, \"origin\":\"colors\"}", Holder.class);
    System.out.println(gson.toJson(holder.getObject()));

Would recommend @bmargulies answer though, that is the right thing to do.

like image 34
Biju Kunjummen Avatar answered Sep 19 '25 20:09

Biju Kunjummen