Gson生成json

时间:2014-11-01 18:06:23

标签: gson

使用Gson,如何生成此格式的json

所需格式:

{
"9912412412":{"name":"nameerra", "email":"varrrr"},
"99349346346":{"email":"varrrr"},
"934636236":{"address":"something"}
}

我的代码生成json数组而不是json

public class ContactsModelRequest extends HashMap<String, ContactsModelRequest.Mobile>{
    public ContactsModelRequest(int size) {
        super(size);
    }
    public static class Mobile {
        public Mobile (String name, String email) {
            this.email = email; this.name = name;
        }
        public String name;
        public String email;
    }
}

Gson gson = new Gson();
gson.getAdapter(ContactsModelRequest.class);
String request = gson.toJson(contactsModel);

1 个答案:

答案 0 :(得分:1)

我认为你不需要ContactsModelRequest。您只需使用HashMap即可。

    Gson gson = new Gson();

    Map<String, Mobile> request = new HashMap<String, Mobile>(3);
    Mobile mobile1 = new Mobile("nameerra", "varrrr", null);
    Mobile mobile2 = new Mobile(null, "varrrr", null);
    Mobile mobile3 = new Mobile(null, null, "something");

    request.put("9912412412", mobile1);
    request.put("99349346346", mobile2);
    request.put("934636236", mobile3);

    String serializedRequest = gson.toJson(request);
    System.out.println("serialized:" + serializedRequest);

    HashMap<String, Mobile> deserializedRequest = gson.fromJson(serializedRequest, new TypeToken<HashMap<String, Mobile>>(){}.getType());

更新您的Mobile POJO并添加address字段,因为您的json示例中有地址字段。

public class Mobile {
    public Mobile(String name, String email, String address) {
        this.email = email;
        this.name = name;
        this.address = address;
    }

    public String name;
    public String email;
    public String address;
}