Question

I'm having a little trouble trying to convert a JSON string from a serialized HTML form to a Java class using Gson.

Here's the example JSON:

[
    { "name" : "ObjectClass", "value" : "Obama" },
    { "name" : "ObjectType", "value" : "Person" },
    { "name" : "Att_1_name", "value" : "Age" }, 
    { "name" : "Att_1_value", "value" : "52" }, 
    { "name" : "Att_2_name", "value" : "Race" },
    { "name" : "Att_2_name", "value" : "African American" }
]

As you can see, it passes an array, then each element of that array consists of a name and a value.

I'm somewhat lost on how to set up my Java class so that Gson can convert it. It should also be noted that the number of elements in the array is variable (there can be as many attributes as the user desires).

My (incorrect) attempt at the class was:

package com.test.objectclasses;

import java.util.ArrayList;

public class tempJSON {
    ArrayList<innerJSON> inJSON;

    public ArrayList<innerJSON> getInJSON() {
        return inJSON;
    }

    public void setInJSON(ArrayList<innerJSON> inJSON) {
        this.inJSON = inJSON;
    }

    public class innerJSON {
        private String name;
        private String value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}

Any idea how to approach this, or am I thinking about it all wrong? Thanks in advance.

Was it helpful?

Solution

First of all, follow Java naming conventions. Your class names should start with a capital letter. So upper camel case.

Get rid of your enclosing class, tempJSON and use a type token in the Gson#fromJson(..) to mark it as a List, since you have a JSON array.

List<innerJSON> innerJSONs = gson.fromJson(yourStream, new TypeToken<List<innerJSON>>(){}.getType());

Now the List will contain as many innerJSON objects as appear in your JSON.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top