How to de-serialize a Map<String, Object> with GSON

 

i am fairly new to GSON and get a JSON response of this format (just an easier example, so the values make no sense):

{
    "Thomas": {
        "age": 32,
        "surname": "Scott"
    },
    "Andy": {
        "age": 25,
        "surname": "Miller"
    }
}

I want GSON to make it a Map, PersonData is obviously an Object. The name string is the identifier for the PersonData.

As I said I am very new to GSON and only tried something like:

Gson gson = new Gson();
Map<String, PersonData> decoded = gson.fromJson(jsonString, new TypeToken<Map<String, PersonData>>(){}.getType());

but this threw the error:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 3141

Any help is appreciated :

Your Json is invalid. Need a comma before "Andy" – Taylor Dec 11 '13 at 15:51
1  
1  
I'm sorry, the JSON is definitely valid. I just shortened the JSON and forgot it. It's more about the GSON part on how to interpret it to key-value where value is an object to be serialized by GSON. – luuksen Dec 11 '13 at 15:53

2 Answers 2

The following works for me

static class PersonData {
    int age;
    String surname;
    public String toString() {
        return "[age = " + age + ", surname = " + surname + "]";
    }
}

public static void main(String[] args) {
    String json = "{\"Thomas\": {\"age\": 32,\"surname\": \"Scott\"},\"Andy\": {\"age\": 25,\"surname\": \"Miller\"}}";
    System.out.println(json);
    Gson gson = new Gson();
    Map<String, PersonData> decoded = gson.fromJson(json, new TypeToken<Map<String, PersonData>>(){}.getType());
    System.out.println(decoded);
}

and prints

{"Thomas": {"age": 32,"surname": "Scott"},"Andy": {"age": 25,"surname": "Miller"}}
{Thomas=[age = 32, surname = Scott], Andy=[age = 25, surname = Miller]}

So maybe your PersonData class is very different.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 
 
    
Okay, I had another problem and I'M sorry that I bothered your time. I had a mistake in my class types that I didn't even post here, but your confirmation that the GSON part works helped me realize where to look at. Thanks! – luuksen Dec 11 '13 at 16:07
    
@luuksen You're welcome. Gson is usually pretty good in its error statements. The BEGIN_ARRAY, BEGIN_OBJECT, NUMBER and STRING will indicate what the Gson parser is actually reading instead of what is expected. – Sotirios Delimanolis Dec 11 '13 at 16:08

 

 

 

You can use gson.toJsonTree(Object o) to convert your custom object to JSON format.

The following works for me:

private static class PersonData {
    private int age;
    private String surname;

    public PersonData(int age, String surname) {
        this.age = age;
        this.surname = surname;
    }
}

public static void main(String[] args) {
    PersonData first = new PersonData(24, "Yovkov");
    PersonData second = new PersonData(25, "Vitanov");

    Gson gson = new Gson();

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("kocko", gson.toJsonTree(first));
    jsonObject.add("deyan", gson.toJsonTree(second));

    System.out.println(gson.toJson(jsonObject));

}

and prints:

{"kocko":{"age":24,"surname":"Yovkov"},"deyan":{"age":25,"surname":"Vitanov"}}

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
164 Java 8 개선 사항 관련 글 모음 졸리운_곰 2016.05.23 271
163 Building a Search Engine With Nutch Solr And Hadoop file 졸리운_곰 2016.04.21 219
162 Nutch and Hadoop Tutorial file 졸리운_곰 2016.04.21 209
161 Latest step by Step Installation guide for dummies: Nutch 0. file 졸리운_곰 2016.04.21 131
160 Nutch 초간단 빌드와 실행 졸리운_곰 2016.04.21 457
159 Nutch로 알아보는 Crawling 구조 - Joinc 졸리운_곰 2016.04.21 352
158 A tiny bittorrent library Java: 자바로 만든 작은 bittorrent 라이브러리 file 졸리운_곰 2016.04.20 242
157 Updating UI in Eclipse RCP 졸리운_곰 2015.11.07 183
156 Eclipse RCP: Display.getDefault().asyncExec still blocking my GUI 졸리운_곰 2015.11.07 135
155 The Eclipse RCP multi-threaded Job and UIJob, use 졸리운_곰 2015.11.07 243
154 SWT: Respond to Long Running Tasks 졸리운_곰 2015.11.07 91
153 SWT and multithreading 졸리운_곰 2015.11.07 73
152 Eclipse RCP multithreading 졸리운_곰 2015.11.07 146
151 Eclipse RCP - Prevent UI freezing while running long operation 졸리운_곰 2015.11.07 114
150 Eclipse RCP Tutorial: How to Add a Progress Bar file 졸리운_곰 2015.11.07 119
149 Eclipse RCP 에서 configuration 설정 파일 사용하지 않기 secret 졸리운_곰 2015.11.07 0
148 Gson User Guide 졸리운_곰 2015.10.26 318
147 Java Google Json (Gson) Type Adapter 졸리운_곰 2015.10.26 145
146 TypeAdapter (Gson 2.3.1 API) - Google Gson 졸리운_곰 2015.10.26 132
145 Gson TypeAdapter Example file 졸리운_곰 2015.10.26 86
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED