0

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.

ev0lution37
  • 1,129
  • 2
  • 14
  • 28
  • Each element of that array is an "object" (Map) containing TWO name/value pairs. (Why the heck they use such a stupid scheme I have no idea.) Also, the final row is miscoded -- it should almost certainly be "att_2_value". – Hot Licks Mar 20 '14 at 01:46
  • Because it is so seriously mucked up I don't see the point in trying to map directly to a Java class. Better to discombobulate the data into a Map of, eg, `{"ObjectClass":"Obama",..."att_2_value":"African American"}` and then, if you still want a Java class, build one from that. – Hot Licks Mar 20 '14 at 01:51
  • Ah, yes!! What someone did is serialize a Map (without realizing it was a Map rather than a custom object) to produce the above JSON. The Map is internally an array of name/value pairs, so that's what the serializer produced. – Hot Licks Mar 20 '14 at 01:55

1 Answers1

0

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724