ruslanys
ruslanys

Reputation: 1211

How to get data from JSON string?

I have a JSON string like this:

{
    "response":[2,
        {
            "id":"187",
            "name":"John",
            "surname":"Corner"
        },
        {
            "id":"254",
            "name":"Bob",
            "surname":"Marley"
        }
    ]
}

How can I parse it using GSON lib in Java? I tried:

static class SearchRequest {
    private Names[] response;

    static class Names {
        private int id;
        private String name;
        private String surname;
    }
}

but it doesn't works :(

Upvotes: 0

Views: 1413

Answers (2)

kornero
kornero

Reputation: 1069

response array contains not only Names, it also contains an integer value: response[0]=2. So you must use something like

private Object[] response;

ADD: I think, you have no need to change your JSON, because your response is private, so you should use getters:

static class SearchRequest {
    private Object[] response;

    static class Names {
        private int id;
        private String name;
        private String surname;
    }

    public List<Names> getNames() {
        List list = new ArrayList();
        list.addAll(Arrays.asList(response));
        return (List<Names>) list.subList(1, response.length);
    }

    public int getAmount() {
        return (Integer) response[0];
    }

    public void setNames(List<Names> names) {
        response = new Object[names.size() + 1];
        response[0] = names.size();
        for (int i = 0, namesSize = names.size(); i < namesSize; i++) {
            response[i + 1] = names.get(i);
        }
    }
}

Upvotes: 2

Juvanis
Juvanis

Reputation: 25950

I prepared a sample code for testing your case, used gson-2.1.jar as library and run it correctly. I modified your JSON string by removing "2," from the beginning of response array since it caused exceptions. Take a look at and test this code:

import com.google.gson.Gson;

public class Test
{
    static class SearchRequest
    {
        private Names [] response;

        static class Names
        {
            private int id;
            private String name;
            private String surname;
        }
    }

    public static void main ( String [] args )
    {
        Gson gson = new Gson();
        String str = "{ \"response\":" 
                   + "[{\"id\":\"187\",\"name\":\"John\",\"surname\":\"Corner\"},"
                   + "{\"id\":\"254\",\"name\":\"Bob\",\"surname\":\"Marley\"}]}";

        SearchRequest request = new SearchRequest();
        request = gson.fromJson( str, SearchRequest.class );
        System.out.println( "name of 1st: " + request.response [ 0 ].name );
        System.out.println( "surname of 2nd: " + request.response [ 1 ].surname );
    }
}

Output:

name of 1st: John
surname of 2nd: Marley

Upvotes: 1

Related Questions