Deserializing a Map<String, Object> field with Gson

 

I have a User object with this structure:
class User {
    private String id;
    private String name;
    private Map<String, Object> properties;

    // GETTERS & SETTERS
}

I have a JSON String with this structure:
{
    "user": {
        "id:"123456789",
        "name:"azerty",
        "emailHash":"123456789", // not used in User class
        "properties": {
            "p1":1,
            "p2":"test",
            "p3":[1, 2, 3, 4],
            "p4":{
               etc...
            }
        }
    }
}

Properties' keys are String, Properties' values can be a String, int, Array, boolean, Map etc.

I try to deserialize this JSON string with Gson like that:
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonString);
JsonObject object = element.getAsJsonObject();

GsonBuilder builder = new GsonBuilder();
builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = builder.create();
User user = (User) gson.fromJson(object.get("user"), new TypeToken<User>() {}.getType());

Fields 'id' and 'name' are correctly injected but the field 'properties' stays null.

Do you know what I'm doing wrong? Thanks in advance for your help!

java json gson


shareimprove this question
 

edited Jan 11 '13 at 8:21

 

 

 

asked Jan 10 '13 at 16:53

 

 
Franck Yapadesouci Anso
153110
 
 
 


      
 
I would suggest having properties as JsonObject and then converting the JSON directly to Map<String,Object>. – Srinivas Jan 10 '13 at 16:58
 

      
 
Your code works perfectly fine with one small problem: you seem to have created a GsonBuilder named builder but are then using one named gsonBuilder. If that's actually compiling then you have another GsonBuilder you previously created and are using it by mistake. Other than that ... it deserializes fine on my machine. – Brian Roach Jan 11 '13 at 3:12 
 

      
 
gsonBuilder is an error when I write the topic. It's builder that I use in my code. I'll edit my topic for correction. The properties field is correctly injected in your test? It's very strange it stays to null for me... – Franck Yapadesouci Anso Jan 11 '13 at 8:20 
 

add a comment 
 

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

 


1 Answer 

 

active

oldest

votes
 


 
up vote

4

down vote

accepted
 

For me this code:
public class Main {
    public static void main(String[] args) throws IOException {
    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    Gson gson = builder.create();
    FileInputStream inputStream = new FileInputStream(new File("bobi.json"));
    InputStreamReader reader = new InputStreamReader(inputStream);
    User user = gson.fromJson(reader, User.class);
    System.out.println(user.getName());
    System.out.println(user.getId());
    for (String property : user.getProperties().keySet()) {
        System.out.println("Key: " + property + " value: " + user.getProperties().get(property));
    }
    reader.close();
}

Prints this:
azerty
123456789
Key: p1 value: 1.0
Key: p2 value: test
Key: p3 value: [1.0, 2.0, 3.0, 4.0]
Key: p4 value: {}

However, keep in mind that I have stripped the wrapping json object in the file I parse. The file is:
{
        "id":"123456789",
        "name" : "azerty",
        "emailHash":"123456789",
        "properties": {
            "p1":1,
            "p2":"test",
            "p3":[1, 2, 3, 4],
            "p4":{

            }
        }
}

Also I added closing double quote for name and id, which you did not have in your sample.

The User class as requested by the OP. I have added getters and setters for the reason of printing:
import java.util.Map;

class User {
    private String id;
    private String name;
    private Map<String, Object> properties;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Map<String, Object> getProperties() {
        return properties;
    }
    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }
}
 

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
169 Mybatis ResultMap 그리고 select 졸리운_곰 2016.06.07 331
168 Mybatis selectList 예제 졸리운_곰 2016.06.05 496
167 java 에서 mybatis 사용한 예제 file 졸리운_곰 2016.06.05 1054
166 [Mybatis] 간단한 마이바티스 CRUD 예제 file 졸리운_곰 2016.06.05 329
165 자바 8 살펴보기 file 졸리운_곰 2016.05.23 338
164 Java 8 개선 사항 관련 글 모음 졸리운_곰 2016.05.23 347
163 Building a Search Engine With Nutch Solr And Hadoop file 졸리운_곰 2016.04.21 276
162 Nutch and Hadoop Tutorial file 졸리운_곰 2016.04.21 258
161 Latest step by Step Installation guide for dummies: Nutch 0. file 졸리운_곰 2016.04.21 186
160 Nutch 초간단 빌드와 실행 졸리운_곰 2016.04.21 528
159 Nutch로 알아보는 Crawling 구조 - Joinc 졸리운_곰 2016.04.21 411
158 A tiny bittorrent library Java: 자바로 만든 작은 bittorrent 라이브러리 file 졸리운_곰 2016.04.20 298
157 Updating UI in Eclipse RCP 졸리운_곰 2015.11.07 270
156 Eclipse RCP: Display.getDefault().asyncExec still blocking my GUI 졸리운_곰 2015.11.07 165
155 The Eclipse RCP multi-threaded Job and UIJob, use 졸리운_곰 2015.11.07 305
154 SWT: Respond to Long Running Tasks 졸리운_곰 2015.11.07 126
153 SWT and multithreading 졸리운_곰 2015.11.07 153
152 Eclipse RCP multithreading 졸리운_곰 2015.11.07 217
151 Eclipse RCP - Prevent UI freezing while running long operation 졸리운_곰 2015.11.07 176
150 Eclipse RCP Tutorial: How to Add a Progress Bar file 졸리운_곰 2015.11.07 181
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED