2017-12-15 4 views
0

Ich habe den folgenden Code, JSON und POJO, obwohl die JSON-Attribute Werte haben, das resultierende DataToUse-Objekt hat Null für Name und Datum. Gibt es eine besondere Möglichkeit, '@' im JSON zu behandeln? Ich habe ein anderes, genau ähnliches Stück Code, das richtig analysiert, aber es gibt kein '@'.Warum analysiert dieser Json mit Null-Attributen?

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; } 
} 
+0

@ Icon vor dem Attributnamen ist, wäre es gut funktionieren, wenn Sie es löschen. –

Antwort

1

unten Versuchen Sie, durch @SerializedName Anmerkung Hinzufügen

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; } 
    } 
-1

Sie sollten die @ aus den Parametern entfernen

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


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

diese Lösung versuchen.

+0

Dies setzt voraus, dass die JSON-Quelle bearbeitbar ist. Wenn es von einer externen API kommt, ist dies unwahrscheinlich –

+0

oh, Ok. Vielen Dank! –

+0

Technisch hätte ich dies auf der Clientseite tun können, indem ich zuerst das JSONObject gepackt habe, es in eine Zeichenkette umgewandelt und dann alle '@' entfernt habe, bevor ich gson.fromJson benutzt habe. Obwohl ich die Antwort bevorzuge, die ich oben gewählt habe, hätte dies auch funktioniert. – KG819

0

Normalerweise müssen Sie bei GSON eine Date-Parsing-Funktion im create gson-Prozess registrieren. Normalerweise mache ich eine Wrapper-Klasse namens JsonHelper, um mein Leben zu erleichtern. Beachten Sie das Datum Umgang Stück. Aber Sie haben wahrscheinlich Probleme mit Ihrem @ -Symbol, aber Sie müssen möglicherweise auch die Datumsformatierung verarbeiten.

/** 
* 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; 
    } 

} 
+0

Dies scheint wie viel Code für das, was gefragt wird –

+0

@ cricket_007 es ist eine Helfer-Klasse, um seine Datenverwaltung zu registrieren. Manchmal ist es schön, eine Lösung aus der Hilfe zu kopieren und einzufügen, anstatt aus Schnipseln, die Sie zusammenfügen müssen. Ich bin gerne gründlich. Der Hauptteil, den er interessieren würde, ist der getGsonBuilder, da dies der Teil ist, den die meisten GSON Benutzer normalerweise überspringen, da sie ihn nicht verstehen oder ihn genug benutzen, um seinen Zweck zu erkennen. – Sam

+0

Ich bin ein 'sie' :) Das Datum hat gut ohne etwas extra analysiert. Ich wusste, dass das funktionieren würde, da ich einen weiteren Aufruf habe, der json ohne '@' Symbole zurückgibt und alles dort ohne Problem analysiert. In diesem Fall war es nur das @ -Zeichen, das besondere Aufmerksamkeit erforderte. – KG819