英文:
Two hashmap to entity class
问题
我有两个`HashMap`,我想使用GSON进行反序列化为实体类。
void convert(){
HashMap<String,String> map1 = new HashMap<>();
map1.put("key1","value1");
map1.put("key2","value2");
HashMap<String,String> map2 = new HashMap<>();
map2.put("key3","value3");
map2.put("key4","value4");
Gson gson = new Gson();
String service = gson.toJson(map2);
map1.put("service", service);
String json = gson.toJson(map1);
MyModel myModel = gson.fromJson(json, MyModel.class);
System.out.println(gson.toJson(myModel));
}
我的实体类
public class MyModel {
String key1;
String key2;
String service;
public String getKey1() {
return key1;
}
public void setKey1(String key1) {
this.key1 = key1;
}
public String getKey2() {
return key2;
}
public void setKey2(String key2) {
this.key2 = key2;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
}
有没有更高效的方法来实现这个?
英文:
I have two HashMap
I want to de-serialize to entity class using GSON.
void convert(){
HashMap<String,String> map1 = new HashMap<>();
map1.put("key1","value1");
map1.put("key2","value2");
HashMap<String,String> map2 = new HashMap<>();
map2.put("key3","value3");
map2.put("key4","value4");
Gson gson = new Gson();
String service = gson.toJson(map2);
map1.put("service", service);
String json = gson.toJson(map1);
MyModel myModel = gson.fromJson(json, MyModel.class);
System.out.println(gson.toJson(myModel));
}
My entity class
public class MyModel {
String key1;
String key2;
String service;
public String getKey1() {
return key1;
}
public void setKey1(String key1) {
this.key1 = key1;
}
public String getKey2() {
return key2;
}
public void setKey2(String key2) {
this.key2 = key2;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
}
Is there any efficient approach to do it.
答案1
得分: 1
你可以直接将 HashMap 转换为 JSON:
HashMap<String, Object> map1 = new HashMap<>();
map1.put("key1", "value1");
map1.put("key2", "value2");
HashMap<String, String> map2 = new HashMap<>();
map2.put("key3", "value3");
map2.put("key4", "value4");
map1.put("service", map2);
String result = gson.toJson(map1);
如果你想将 JSON 转换为实体类(Entity class):
MyModel myModel = gson.fromJson(result, MyModel.class);
并且在 service
字段中使用 Map<String, String>
:
public class MyModel {
String key1;
String key2;
Map<String, String> service;
// ...
}
英文:
You can directly convert HashMap to json
HashMap<String,Object> map1 = new HashMap<>();
map1.put("key1","value1");
map1.put("key2","value2");
HashMap<String,String> map2 = new HashMap<>();
map2.put("key3","value3");
map2.put("key4","value4");
map1.put("service", map2);
String result = gson.toJson(map1);
And if you want convert json to Entity class
MyModel myModel = gson.fromJson(result, MyModel.class);
And use Map<String,String>
for service field
public class MyModel {
String key1;
String key2;
Map<String,String> service;
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论