问题
I am using Gson for converting my Java Objects to GSON. I wanted to convert my HashMap to JSON.
Assuming my Object1 has structure:
public class Object1 {
String a;
String b;
String c;
String toString() {
return "a: " + a + " b: " + b + " c: " + c;
}
}
and my Object2 has Structure:
public class Object2 {
String e;
String f;
}
I wanted my final JSON to look like
{
{
"a" : "aValue",
"b" : "bValue",
"c" : "cValue"
} : {
"e" : "eValue",
"f" : "fValue"
}
}
Bit I am getting it as
{
"a: aValue b: bValue c: cValue" : {
"e" : "eValue",
"f" : "fValue"
}
}
Is this possible to have it in desired form.
I tried using TypeToken given in JSON documentation. That didn't help.
回答1:
You cannot get your expected form.
JSON's element is always a key-value paar and the key is always a text (or String). But in your case the key is an object.
From my understanding, if you wanna to consume the key as an Object, you could get it as a String and then use ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper) to convert it to your expected class.
final ObjectMapper mapper = new ObjectMapper();
Object1 object1 = mapper.readValue(object1String, Object1.class)
回答2:
Your toString() method may be causing issues, Gson will process the map itself, there is no need to provide a toString() like you have. That's why your output is giving you that.
Also take a look at Jackson, it would be fit for your purpose and is very easy to use.
Map map = new HashMap();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
// write json to file
回答3:
You can write your toString method as:
public String toString() {
return "{a: " + a + ", b: " + b + ", c: " + c + "}";
}
In your main class, you call:
public static void main(String[] args) {
Object1 object1 = new Object1("aValue", "bValue", "cValue");
Object2 object2 = new Object2("eValue", "fValue");
Map<String, Object2> map = new HashMap<String, Object2>();
map.put(object1.toString(), object2);
String json = new Gson().toJson(map);
}
Then, your output like: {"{a: aValue, b: bValue, c: cValue}":{"e":"eValue","f":"fValue"}}
来源:https://stackoverflow.com/questions/39657154/hashmap-to-json-using-gson