猿问

android 读取json 为什么不直接反序列化

如题,为什么不直接创建json 对应的实体,再反序列化,然后直接拿到完整的对象。我看到一些人都是去遍历json 数组。。然后再封装。。不理解为什么要这样做,我不是搞android的,轻点拍我。

函数式编程
浏览 609回答 4
4回答

HUX布斯

不知道我这种情况是否算一个原因,在从服务器端传回处理结果的时候。我需要知道服务器端处理的是否成功,所以我会把结果封包到两个子的json 中,一个用来指示处理状态,另一个才是结果。这先解析第一个json 包,然后决定如何处理第二个json 的数据。

江户川乱折腾

json是一种通用格式,服务器返回json,不把json转成java对象,还能怎样?

手掌心

如果取到json后只拿map传递是可行的,而且效率高了那么一丢丢。但是一是维护成本变得高多了吧,下一个接手的人面对一大堆map怎么搞;二是不符合mvc的思想,map与View之间是强耦合的,如果是javabean的话,可以有很多方案去解耦

幕布斯7119047

我们平时写的bean类,这个是指定规则的序列化对象,虚拟机认得,你说用json反序列化获取对象,这个规则是后台定的,虚拟机如何认得?而且你说的,很多人一直遍历json字符串,然后一个字段一个字段的封装,超级麻烦,我也不知道他们为什么这么做?不管是解析成object对象还是list数据,我都有自己封装的工具,就两三行代码.如下:private static Gson sGson;&nbsp; &nbsp; public static Gson getGson() {&nbsp; &nbsp; &nbsp; &nbsp; if (null == sGson) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sGson = new Gson();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return sGson;&nbsp; &nbsp; }/**&nbsp; &nbsp; &nbsp;* 将json字符串转换成一个对象&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param jsonStr json字符串&nbsp; &nbsp; &nbsp;* @param field&nbsp; &nbsp;字段名&nbsp; &nbsp; &nbsp;* @param clazz&nbsp; &nbsp;字节码&nbsp; &nbsp; &nbsp;* @param <T>&nbsp; &nbsp; &nbsp;类型&nbsp; &nbsp; &nbsp;* @return&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public static <T> T getObject(String jsonStr, String field, Class<T> clazz) {&nbsp; &nbsp; &nbsp; &nbsp; JSONObject jsonObject = getJSONObject(jsonStr);&nbsp; &nbsp; &nbsp; &nbsp; T t = getGson().fromJson(jsonObject.optString(field), clazz);&nbsp; &nbsp; &nbsp; &nbsp; return t;&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* 将json字符串转换成list数据&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param json&nbsp; &nbsp; &nbsp;* @param clazz&nbsp; &nbsp; &nbsp;* @param <T>&nbsp; &nbsp; &nbsp;* @return&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public static <T> List<T> getList(String json, Class<T> clazz) {&nbsp; &nbsp; &nbsp; &nbsp; List<T> list = null;&nbsp; &nbsp; &nbsp; &nbsp; list = JSON.parseArray(json, clazz);&nbsp; &nbsp; &nbsp; &nbsp; return list;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;/**&nbsp; &nbsp; &nbsp;* 将json字符串转换成jsonObject&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param jsonStr&nbsp; &nbsp; &nbsp;* @return&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public static JSONObject getJSONObject(String jsonStr) {&nbsp; &nbsp; &nbsp; &nbsp; JSONObject mJson = new JSONObject();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mJson = new JSONObject(jsonStr);&nbsp; &nbsp; &nbsp; &nbsp; } catch (JSONException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return mJson;&nbsp; &nbsp; }这个是我个人的理解,也没有权威的认证过.
随时随地看视频慕课网APP

相关分类

Java
我要回答