【问题标题】:Why does this json parse with null attributes?为什么这个 json 解析为空属性?
【发布时间】:2017-12-15 16:40:27
【问题描述】:

我有以下代码,JSON 和 POJO,但是即使 JSON 属性具有值,生成的 dataToUse 对象的名称和日期也为 null。有没有一种特殊的方法来处理 json 中的“@”?我有另一段完全相似的代码可以正确解析,但没有'@'。

DataToUse dataToUse = new Gson().fromJson(json.toString(), DataToUse.class);

JSON:

{“@name”: “A Name”,“@date”: "2017-12-11T18:00:00-05:00"}

POJO:

public class DataToUse {
    private String name;
    private Date date;

    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }

    public Date getDate() { return this.date; }
    public void setDate(Date date) { this.date = date; }
}

【问题讨论】:

  • 属性名前有@图标,删除即可。

标签: java android json gson pojo


【解决方案1】:

试试下面,通过添加@SerializedName注解

    public class DataToUse {
        @SerializedName("@name")
        private String name;
        @SerializedName("@date")
        private Date date;

        public String getName() { return this.name; }
        public void setName(String name) { this.name = name; }

        public Date getDate() { return this.date; }
        public void setDate(Date date) { this.date = date; }
    }

【讨论】:

    【解决方案2】:

    通常使用 GSON,您需要在创建 gson 过程中注册日期解析功能。我通常会创建一个名为 JsonHelper 的包装类来让我的生活更轻松。注意日期处理部分。但是您的 @ 符号可能有问题,但您可能还需要处理日期格式。

    /**
     * Created by App Studio 35 on 3/18/15.
     */
    public class JSONHelper {
    
        /*//////////////////////////////////////////////////////////
        // MEMBERS
        *///////////////////////////////////////////////////////////
        private static Gson mGson; //Google's JSON to Object Converter
        private static final String TAG = JSONHelper.class.getSimpleName();
    
    
        /*//////////////////////////////////////////////////////////
        // PROPERTIES
        *///////////////////////////////////////////////////////////
        protected static Gson getGson(){
            return mGson == null ? mGson = getGsonBuilder().create() : mGson;
        }
    
    
        /*//////////////////////////////////////////////////////////
        // METHODS
        *///////////////////////////////////////////////////////////
        private static GsonBuilder getGsonBuilder(){
            //Used for Building a Gson Converter a Google Product for JSON Translation to Objects
            GsonBuilder builder = new GsonBuilder();
            //Created as Static so Fragments can easily use the same Builder.
            builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
    
                @Override
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    
                    //Specify the way we format Dates in this Converter
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.getDefault());
                    format.setTimeZone(TimeZone.getTimeZone("UTC"));
                    String date = json.getAsJsonPrimitive().getAsString();
    
                    try {
                        return format.parse(date);
    
                    } catch (ParseException e) {
                        Log.e(TAG, "getGsonBuilder failed to register Date: " + e.getMessage());
                        throw new RuntimeException(e);
    
                    }
                }
            });
            return builder;
        }
        /**
         *
         * @param objectToConvert to convert to Json
         * @param classType the class that we are serializing from into a String
         * @return
         */
        public static String toJson(Object objectToConvert, Class classType){
            try {
                String msg = "";
                //Get String from Gson converter for Class Type
                msg = getGson().toJson(objectToConvert, classType);
    
                //Return String of Json from passed in Object
                return msg;
    
            } catch (Exception e) {
                Log.e(TAG, e.getMessage() == null ? "null" : e.getMessage());
                return "";
    
            }
        }
        /**
         *
         * @param objectToConvert to convert to Json
         * @param classType the Type that we are serializing from into a String
         * @return
         */
        public static String toJson(Object objectToConvert, Type classType){
            try {
                String msg = "";
                //Get String from Gson converter for Class Type
                msg = getGson().toJson(objectToConvert, classType);
    
                //Return String of Json from passed in Object
                return msg;
    
            } catch (Exception e) {
                Log.e(TAG, e.getMessage() == null ? "null" : e.getMessage());
                return "";
    
            }
        }
        /**
         *
         * @param objectToConvert Object to convert to JSON string
         * @return json string to represent the passed object
         */
        public static String toJson(Object objectToConvert){
            try {
                String msg = "";
                //Get String from Gson converter for Class Type
                msg = getGson().toJson(objectToConvert);
    
                //Return String of Json from passed in Object
                return msg;
    
            } catch (Exception e) {
                Log.e(TAG, e.getMessage() == null ? "null" : e.getMessage());
                return "";
    
            }
        }
        /**
         *
         * @param json String to convert into Object for the class that was passed
         * @param classType the class that we are serializing from
         * @return
         */
        public static Object fromJson(String json, Class classType){
            try {
                //Get Object from Gson converter of Json
                Object obj = getGson().fromJson(json, classType);
    
                //Return filled in object of passed in Class Type
                return obj;
    
            } catch (Exception e) {
                Log.e(TAG, e.getMessage() == null ? "null" : e.getMessage());
                return null;
    
            }
        }
        /**
         *
         * @param json String to convert into Json for the class that was passed
         * @param classType the Type that we are serializing from
         * @return
         */
        public static Object fromJson(String json, Type classType){
            try {
                //Get Object from Gson converter of Json
                Object obj = getGson().fromJson(json, classType);
    
                //Return filled in object of passed in Class Type
                return obj;
    
            } catch (Exception e) {
                Log.e(TAG, e.getMessage() == null ? "null" : e.getMessage());
                return null;
    
            }
        }
        /**
         *
         * @param jsonElement JsonElement to convert into Object for the class that was passed
         * @param classType the class that we are serializing from
         * @return
         */
        public static Object fromJson(JsonElement jsonElement, Class classType){
            try {
                //Get Object from Gson converter of Json
                Object obj = getGson().fromJson(jsonElement, classType);
    
                //Return filled in object of passed in Class Type
                return obj;
    
            } catch (Exception e) {
                Log.e(TAG, e.getMessage() == null ? "null" : e.getMessage());
                return null;
    
            }
        }
        /**
         *
         * @param jsonElement String to convert into Object for the class that was passed
         * @param classType the class that we are serializing from
         * @return
         */
        public static Object fromJson(JsonElement jsonElement, Type classType){
            try {
                //Get Object from Gson converter of Json
                Object obj = getGson().fromJson(jsonElement, classType);
    
                //Return filled in object of passed in Class Type
                return obj;
    
            } catch (Exception e) {
                Log.e(TAG, e.getMessage() == null ? "null" : e.getMessage());
                return null;
    
            }
        }
        public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
            Map<String, Object> retMap = new HashMap<String, Object>();
    
            if(json != JSONObject.NULL) {
                retMap = toMap(json);
            }
            return retMap;
        }
        public static Map<String, Object> toMap(JSONObject object) throws JSONException {
            Map<String, Object> map = new HashMap<String, Object>();
    
            Iterator<String> keysItr = object.keys();
            while(keysItr.hasNext()) {
                String key = keysItr.next();
                Object value = object.get(key);
    
                if(value instanceof JSONArray) {
                    value = toList((JSONArray) value);
                }
    
                else if(value instanceof JSONObject) {
                    value = toMap((JSONObject) value);
                }
                map.put(key, value);
            }
            return map;
        }
        public static List<Object> toList(JSONArray array) throws JSONException {
            List<Object> list = new ArrayList<Object>();
            for(int i = 0; i < array.length(); i++) {
                Object value = array.get(i);
                if(value instanceof JSONArray) {
                    value = toList((JSONArray) value);
                }
    
                else if(value instanceof JSONObject) {
                    value = toMap((JSONObject) value);
                }
                list.add(value);
            }
            return list;
        }
    
    }
    

    【讨论】:

    • 这似乎需要很多代码来解决问题
    • @cricket_007 这是一个帮助类来注册他的日期管理。有时,从帮助中获得一个复制和粘贴解决方案而不是你必须拼凑起来的 sn-ps 是很好的。我喜欢彻底。他关心的主要部分是 getGsonBuilder,因为这是大多数 GSON 用户通常会跳过的部分,因为他们不理解它或使用它来识别它的用途。
    • 我是“她”:) 日期解析得很好,没有任何额外内容。我知道这会起作用,因为我有另一个调用返回没有“@”符号的 json,并且那里的所有内容都可以毫无问题地解析。在这种情况下,真正需要特别注意的只是“@”符号。
    【解决方案3】:

    您应该从参数中删除@

    {“@name”: “A Name”,“@date”: "2017-12-11T18:00:00-05:00"}
    
    
    {“name”: “A Name”,“date”: "2017-12-11T18:00:00-05:00"}
    

    试试这个解决方案。

    【讨论】:

    • 这假定 JSON 源是可编辑的。如果它来自外部 API,则不太可能
    • 哦,好的。谢谢!
    • 从技术上讲,我可以在客户端完成此操作,首先获取 JSONObject,将其转换为字符串,然后在使用 gson.fromJson 之前删除所有“@”。虽然我更喜欢上面选择的答案,但这也可以。
    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 2011-07-11
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多