Burferd
Burferd

Reputation: 2491

Json/Gson issue - Why am I getting null?

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; }

}

Upvotes: 1

Views: 304

Answers (1)

Kiril
Kiril

Reputation: 40345

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?

Upvotes: 1

Related Questions