|
| 1 | +package cn.aofeng.demo.json.gson; |
| 2 | + |
| 3 | +import java.lang.reflect.Type; |
| 4 | + |
| 5 | +import com.google.gson.Gson; |
| 6 | +import com.google.gson.GsonBuilder; |
| 7 | +import com.google.gson.JsonDeserializationContext; |
| 8 | +import com.google.gson.JsonDeserializer; |
| 9 | +import com.google.gson.JsonElement; |
| 10 | +import com.google.gson.JsonObject; |
| 11 | +import com.google.gson.JsonParseException; |
| 12 | + |
| 13 | +/** |
| 14 | + * 自定义反序列化。 |
| 15 | + * |
| 16 | + * @author <a href="mailto:[email protected]">聂勇</a> |
| 17 | + */ |
| 18 | +public class CustomDeserialize { |
| 19 | + |
| 20 | + public static void main(String[] args) { |
| 21 | + GsonBuilder builder = new GsonBuilder(); |
| 22 | + builder.registerTypeAdapter(Person.class, new PersonDeserializer()); |
| 23 | + Gson gson = builder.create(); |
| 24 | + |
| 25 | + String json = "{\"PersonName\":\"aofeng\",\"PersonAge\":32}"; |
| 26 | + Person obj = gson.fromJson(json, Person.class); |
| 27 | + System.out.println(obj); // 输出结果:Person [name=aofeng, age=32] |
| 28 | + } |
| 29 | + |
| 30 | + public static class PersonDeserializer implements JsonDeserializer<Person> { |
| 31 | + |
| 32 | + @Override |
| 33 | + public Person deserialize(JsonElement jsonEle, Type type, |
| 34 | + JsonDeserializationContext context) |
| 35 | + throws JsonParseException { |
| 36 | + JsonObject jo = jsonEle.getAsJsonObject(); |
| 37 | + String name = jo.get("PersonName").getAsString(); |
| 38 | + int age = jo.get("PersonAge").getAsInt(); |
| 39 | + |
| 40 | + Person obj = new Person(name, age); |
| 41 | + return obj; |
| 42 | + } |
| 43 | + |
| 44 | + } // end of PersonDeserializer |
| 45 | + |
| 46 | +} |
0 commit comments