1

Please i have a json response String like this:

{"result":{"id":21456,"name":"3mm nail","type":"2" }}

and this is my code:

class rootObj{
    List<Result> result;

}
public class Result {
    @SerializedName("id")
    public String idItem;

    @SerializedName("name")
    public String name;    
}
public static void main(String[] args) throws Exception {
Gson gson = new Gson();
Result result = gson.fromJson(json,Result.class);
System.out.println(result.name);
}

But the result is null :( Thx in advance.

So.. This code is what i was aiming:

class ResultData{

    private Result result;
    public class Result {
        private String id;
        private String name;

    }

}


...
Gson gson = new Gson();
ResultData resultData = new Gson().fromJson(json, ResultData.class);

System.out.println(resultData.result.id);
System.out.println(resultData.result.name);

Thx to BalusC gave me the idea about it. Java - Gson parsing nested within nested

Community
  • 1
  • 1
AlfaTango
  • 23
  • 5
  • 2
    I don't know Gson, but two things jump out: 1. You're asking it to treat a number (`id`) as a string. Is that intentional? Will Gson do that automatically? 2. You haven't mapped the `type` property, is Gson happy with leaving out properties? – T.J. Crowder Mar 29 '13 at 12:06
  • the id is really so, about the type i just edit it now is correct. – AlfaTango Mar 29 '13 at 12:10
  • In your Result class you have not declared the "type" object? – Lakshmi Mar 29 '13 at 12:23

2 Answers2

2

In your JSON string your result property is an Object not an Array. So to make it work with your two Java classes (rootObj and Result) you need to add [brackets] around your {braces} Original

{"result":{"id":21456,"name":"3mm nail","type":"2" }}

New

{"result":[{"id":21456,"name":"3mm nail","type":"2" }]}

This code works for me:

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

public class TestGson {
    private static final String NAME = "3mm nail";

    @Test
    public void testList() {
        final String json = "{\"result\":[{\"id\":21456,\"name\":\"" + NAME + "\",\"type\":\"2\" }]}";
        Gson gson = new Gson();
        ListWrapper wrapper = gson.fromJson(json, ListWrapper.class);
        assertEquals(NAME, wrapper.result.get(0).name);
    }

    static class ListWrapper {
        List<Result> result;
    }

    static class ObjectWrapper {
        Result result;
    }

    static class Result {
        @SerializedName("id")
        public int idItem;

        @SerializedName("name")
        public String name;
    }

}
marc2112
  • 153
  • 1
  • 7
0

refer this ..It explaining how to parse the json without using the GSON

bCliks
  • 2,918
  • 7
  • 29
  • 52