Json/Gson issue - Why am I getting null?

Go To StackoverFlow.com

1

I'm trying to put together something to decode a Json string and not having much luck.

Right now, I'm attempting to read a file and parse that into it's components. I can read the status value just fine, but when I attempt to read the list, I get null, and I don't understand why.

Can anyone show me what I am doing wrong?

Here is the contents of the file:

{
    "results" : [
        { 
            "long_name" : "Long Name 1",
            "short_name" : "Short Name 1"
        },
        {
            "long_name" : "Long Name 2",
            "short_name" : "Short Name 2"
        }
    ],
    "status" : "OK"
}

Here is the code I am using to parse the file after it is read:

            BufferedReader br =
            new BufferedReader( new FileReader(aFile));
            StringBuilder builder = new StringBuilder();
            String st;
            for (String line = null; (line = br.readLine()) != null;) 
            {
                st = line.trim();
                builder.append(st);
            }
            br.close();
            String data = builder.toString();
            Results rslt = new Gson().fromJson( data, Results.class );
            List<ResultsData> resultsData = rslt.getResultsData();
            System.out.println( "ResultsData      : "+resultsData );       // This is null
            System.out.println( "Status           : "+rslt.getStatus() );  // This is OK

Here are the two classes I am using for parsing:

import java.util.List;

public class Results {

    private List<ResultsData> resultsData;
    public List<ResultsData> getResultsData() { return resultsData; }
    public void setResultsData( List<ResultsData> l ) { resultsData = l; }

    private String status;
    public String getStatus() { return status; }
    public void setStatus( String s ) { status = s; }

}

And

public class ResultsData {

    private String long_name = "";
    public String getLong_name() {return long_name;}
    public void setLong_name( String s ) { long_name = s; }

    private String short_name = "";
    public String getShort_name() {return short_name;}
    public void setShort_name( String s ) { short_name = s; }

}
2012-04-03 20:30
by Burferd


1

I would guess it's because the JSon file says results and the corresponding field in the Result class is named resultsData. In other words: the schema doesn't match. So what does your schema look like?

2012-04-03 20:33
by Kiril
+1 in addition, it looks like you can also add this annotation @SerializedName("name") to go around this issue without changing your java code. Alternatively, you can use the FieldNamingPolicyGuillaume Polet 2012-04-03 20:47
^ good point :) == 1 UP from me - Kiril 2012-04-03 20:50
Thanks, Obviously, I'm a Gson/Json novice. I'm not sure what the @SerializedName("name") reference means. Could you explain a bit - Burferd 2012-04-03 21:24
Ads