The Tokenizer The Tokenizer - 3 months ago 17
JSON Question

trouble parsing w/ Gson. BEGIN_OBJECT at line 1 column 10

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 10 path $.noun


Hi all, I need helping parsing a json response that looks like the one I have below. I've been using Gson but I can't seem to get past this error message (or similar messages depending on my changes).

{
noun: {
syn: [
"passion",
"beloved",
"sexual activity",
"sexual desire",
"sexual practice"
],
ant: [
"hate"
],
usr: [
"amour"
]
},
verb: {
syn: [
"love",
"enjoy",
"mate",
"pair"
],
ant: [
"hate"
]
}
}


I've created a few classes(noun,verb,adj,etc..) to handle my responses like:

public class Noun extends WordSubType {
private static final String TAG = "Noun";

@SerializedName("noun")
public String noun;

public Noun(String[] synonym, String[] antonym, String[] related, String[] similar, String[] user_suggestions) {
super(synonym, antonym, related, similar, user_suggestions);
}
}


and

public class WordSubType {
private static final String TAG = WordSubType.class.getSimpleName();

@SerializedName("syn")
private String[] synonym;

@SerializedName("ant")
private String[] antonym;

@SerializedName("rel")
private String[] related;

@SerializedName("sim")
private String[] similar;

@SerializedName("usr")
private String[] user_suggestions;


public WordSubType(String[] synonym,
String[] antonym,
String[] related,
String[] similar,
String[] user_suggestions) {
this.synonym = synonym;
this.antonym = antonym;
this.related = related;
this.similar = similar;
this.user_suggestions = user_suggestions;
}

public String[] getSynonym() {
return synonym;
}

public String[] getAntonym() {
return antonym;
}


Trying to parse the first object with this code:

public void parse(String jsonLine) {
Gson gson = new Gson();
Type collectionType = new TypeToken<Noun>(){}.getType();
Collection<Noun> enums = gson.fromJson(jsonLine, collectionType);
}

Answer

You actually need a class to represent your response, or you have to extract your components manually.

class Response {

    private WordSubType noun;
    private WordSubType verb;
    //... Others

}

You can now deserialize with:

Response r = gson.fromJson(json, Response.class);
Comments