2015-11-20 109 views
0

我在我的android应用程序中使用GSON。目前,我正在设置一个方法,该方法包含来自我的JSON字符串的一个值,名为“followed”。 JSON字符串中的项目之一包含后面的内容,而第二个字符串不包含。我使用Realm来坚持独特的对象,以便您可以看到它被覆盖。GSON忽略JSON字符串中的缺失值

这里是2个JSON字符串进行比较,例如:

{"customer_case":"OFFICE001","circle_id":"3","address":"10 Canal St","city":"Bristol","state":"PA","zip":"19007","county":"Bucks County","apt_no":"","latitude":"40.1012666","longitude":"-74.855304","profile_picture":"uploads/thumbnails/2014/06/07/16/1402165202_3_16_539356ad9134b3.jpg","id":"539356ad9134b3","google_address":"10 Canal Street","google_city":"Bristol","google_state":"Pennsylvania","verified_zip":"19007","google_county":"Bucks County","status":"Active","add_date":"2014-06-07","circle_name":"Test Portfolio","step":"Rental","loan":"","winterized":null,"boiler":null,"sump_pump":null,"septic":null,"police_id":null,"police":null,"police_phone":null,"electric_id":null,"electric":null,"electric_phone":null,"sewer_id":null,"sewer":null,"sewer_phone":null,"water_id":null,"water":null,"water_phone":null,"fsm_company_id":"5","fsm_company":"Assero Services LLC - FSM","fsm_email":"[email protected]","fsm_phone":"2155868317","hoa_id":null,"hoa":null,"hoa_email":null,"hoa_phone":null,"client_id":"9","client":"Test Client","client_email":"[email protected]","client_phone":"2157830782","broker_contact_id":null,"broker":null,"broker_email":null,"broker_phone":null,"lawn_contractor":null,"cleaning_contractor":null,"bedroom":null,"bathroom":null,"sqft":null,"lot_size":null,"list_price":"538525","built":null,"assign_date":"06/07/2014","lock_box":null,"gate_code":null,"key_code":null,"property_type":"Unknown","description":null,"sub_status":null,"occupancy_status":null,"street_view":"uploads/2015/06/25/4036/0470e4cd-ce9d-4439-8031-6be5101cd09c.JPG","marketing_front":"uploads/2015/06/25/4036/b099a190-f354-454a-8479-bec67bc41988.JPG","followed":"1"} 
{"customer_case":"OFFICE001","circle_id":"3","address":"10 Canal St","city":"Bristol","state":"PA","zip":"19007","county":"Bucks County","apt_no":"","latitude":"40.1012666","longitude":"-74.855304","profile_picture":"uploads/thumbnails/2014/06/07/16/1402165202_3_16_539356ad9134b3.jpg","id":"539356ad9134b3","google_address":"10 Canal Street","google_city":"Bristol","google_state":"Pennsylvania","verified_zip":"19007","google_county":"Bucks County","status":"Active","add_date":"2014-06-07","circle_name":"Test Portfolio","step":"Rental","loan":"","winterized":null,"boiler":null,"sump_pump":null,"septic":null,"police_id":null,"police":null,"police_phone":null,"electric_id":null,"electric":null,"electric_phone":null,"sewer_id":null,"sewer":null,"sewer_phone":null,"water_id":null,"water":null,"water_phone":null,"fsm_company_id":"5","fsm_company":"Assero Services LLC - FSM","fsm_email":"[email protected]","fsm_phone":"2155868317","hoa_id":null,"hoa":null,"hoa_email":null,"hoa_phone":null,"client_id":"9","client":"Test Client","client_email":"[email protected]","client_phone":"2157830782","broker_contact_id":null,"broker":null,"broker_email":null,"broker_phone":null,"lawn_contractor":null,"cleaning_contractor":null,"bedroom":null,"bathroom":null,"sqft":null,"lot_size":null,"list_price":"538525","built":null,"assign_date":"06/07/2014","lock_box":null,"gate_code":null,"key_code":null,"property_type":"Unknown","description":null,"sub_status":null,"occupancy_status":null,"street_view":"uploads/2015/06/25/4036/0470e4cd-ce9d-4439-8031-6be5101cd09c.JPG","marketing_front":"uploads/2015/06/25/4036/b099a190-f354-454a-8479-bec67bc41988.JPG"} 

注意的差值为JSON字符串的末尾被跟随项。

从GSON文档中可以看到: “虽然反序列化,但JSON中缺少的项导致将对象中的相应字段设置为null。”

有没有办法来覆盖这个并不会自动将其设置为空,而只是跳过字段?

下面是一些代码,我使用的反序列化的json:

PropertyObject prop = visnetawrap.gsonClient.fromJson(properties.get(i).toString(), PropertyObject.class); 

visnetawrap.gsonClient = new GsonBuilder() 
      .setExclusionStrategies(new ExclusionStrategy() { 
       @Override 
       public boolean shouldSkipField(FieldAttributes f) { 
        return f.getDeclaringClass().equals(RealmObject.class) || f.getDeclaredClass().equals(Drawable.class); 
       } 

       @Override 
       public boolean shouldSkipClass(Class<?> clazz) { 
        return false; 
       } 
      }) 
      .registerTypeAdapter(Date.class, new GsonDateDeserializer()) 
      .registerTypeAdapter(Double.class, new TypeAdapter<Double>() { 
       @Override 
       public void write(JsonWriter out, Double value) throws IOException { 
        if (value == null) { 
         out.nullValue(); 
         return; 
        } 
        out.value(value); 
       } 

       @Override 
       public Double read(JsonReader in) throws IOException { 
        if (in.peek() == JsonToken.NULL) { 
         in.nextNull(); 
         return null; 
        } 
        String stringValue = in.nextString(); 
        try { 
         return Double.valueOf(stringValue); 
        } catch (NumberFormatException e) { 
         return null; 
        } 
       } 
      }) 
      .create(); 

回答

0

你就可以创造自己的TypeAdapter

public class YourTypeAdapter extends TypeAdapter<PropertyObject> { 

    @Override 
    public PropertyObject read(final JsonReader in) throws IOException { 
    final PropertyObject obj = new PropertyObject(); //I don't know how is your obj 

    in.beginObject(); 
    boolean hasFollowedField = false; 
    while (in.hasNext()) { 

     switch (in.nextName()) { 
     case "gate_code": 
     //set value to your obj 
     obj.setValue(in.nextString()) 
     break; 
     //do same thing to others... 
     //... 
     case "followed": 
     hasFollowedField = true; 
     //set value to obj 
     break; 
     } 
     if (!hasFollowedField) { 
     //set followed value to obj what you want 
     } 
    } 
    in.endObject(); 

    return obj; 
    } 

    @Override 
    public void write(final JsonWriter out, final PropertyObject obj) throws IOException { 
    out.beginObject(); 
    out.name("gate_code").value(gate_code.getGateCode()); 
    //simple set name and value from obj to JsonWriter 
    out.endObject(); 
    } 
} 

,然后注册TypeAdapter您GsonBuilder OBJ

希望这会有所帮助

+0

让我试试看,让你知道它是如何工作的,我需要做每个名字或只是按照? –

+0

是的,你需要做每个名字。 – calvinfly

+0

该死的,我有很多哈哈。我将有机会明天尝试,会回来。 –

0

这就是我所做的g作为一个工作:

.registerTypeAdapter(PropertyObject.class, new JsonDeserializer<PropertyObject>() { 
       @Override 
       public PropertyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
        PropertyObject prop = new PropertyObject(); 
        JsonObject propObj = json.getAsJsonObject(); 

        if (propObj.get("id") == null) { 
         return null; 
        } 

        prop.setPropertyId(propObj.get("id").getAsString()); 

        if (propObj.get("followed") == null) { 
         Realm realmThread = Realm.getDefaultInstance(); 

         PropertyObject existingProp = realmThread.where(PropertyObject.class).equalTo("propertyId", propObj.get("id").getAsString()).findFirst(); 
         if (existingProp == null) { 
          prop.setPropertyFollowed(0); 
         } 
         else { 
          prop.setPropertyFollowed(existingProp.getPropertyFollowed()); 
         } 

         realmThread.close(); 
        } 
        else { 
         prop.setPropertyFollowed(propObj.get("followed").getAsInt()); 
        } 

        return prop; 
       } 
      })