Java – analyze JSON map / dictionary with gson?
•
Java
I need to parse the JSON response:
{"key1": "value1","key2": "value2","key3": {"childKey1": "childValue1","childKey2": "childValue2","childKey3": "childValue3" } } class Egg { @SerializedName("key1") private String mKey1; @SerializedName("key2") private String mKey2; @SerializedName("key3") // ??? }
I'm reading the gson document, but I can't figure out how to properly deserialize the dictionary into a map
Solution
Gson can easily handle the deserialization of a JSON object, whose name is: value pair to Java map
The following is an example of JSON using the original problem (this example also demonstrates how to use fieldnaming strategy to avoid specifying serialization names for each field, provided that the field to element name mapping is consistent.)
import java.io.FileReader; import java.lang.reflect.Field; import java.util.Map; import com.google.gson.FieldNamingStrategy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Foo { public static void main(String[] args) throws Exception { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingStrategy(new MyFieldNamingStrategy()); Gson gson = gsonBuilder.create(); Egg egg = gson.fromJson(new FileReader("input.json"),Egg.class); System.out.println(gson.toJson(egg)); } } class Egg { private String mKey1; private String mKey2; private Map<String,String> mKey3; } class MyFieldNamingStrategy implements FieldNamingStrategy { //Translates the Java field name into its JSON element name representation. @Override public String translateName(Field field) { String name = field.getName(); char newFirstChar = Character.toLowerCase(name.charAt(1)); return newFirstChar + name.substring(2); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码