2013-03-25 25 views
7

Bir şey ters giderse sonuç olarak ExceptionEntity seri hale getirilmiş sınıfı döndüren REST hizmeti oluşturdum.Gson.fromJson() - Type farklıysa istisna atar

Gson.fromJson() tarafından serileştirilmesi gereken json'un farklı türde olması durumunda bir istisna atmak istiyorum. Mesela ben serileştirilemezse edilmelidir Bu dize (my.ExceptionEntity.class) var:

{"exceptionId":2,"message":"Room aaaa already exists."} 

ama bu dizgeleştirilmiş için türü olarak Room sınıfını kullanın:

String json = "{\"exceptionId\":2,\"message\":\"Room aaaa already exists.\"}"; 
Room r = gson.fromJson(json, Room.class); 
// as a result r==null but I want to throw Exception; how? 

[DÜZENLE] bunu test ettik ve onu çalışmıyor:

try { 
    return g.fromJson(roomJson, new TypeToken<Room>(){}.getType()); 
    // this also doesn't work 
    // return g.fromJson(roomJson, Room.class); 
} catch (JsonSyntaxException e) { 
    pepuch.multiplayergame.entity.Exception ex = g.fromJson(roomJson, pepuch.multiplayergame.entity.Exception.class); 
    throw ExceptionController.toGameServerException(ex); 
} catch (JsonParseException e) { 
    pepuch.multiplayergame.entity.Exception ex = g.fromJson(roomJson, pepuch.multiplayergame.entity.Exception.class); 
    throw ExceptionController.toGameServerException(ex); 
} 
+0

olası kopya ile çalışmalısınız özel bir istisna sağlamak istiyorsanız bu, bir kontrolsüz istisnadır (http://stackoverflow.com/questions/ [GSON yanlış türlerinde istisnalar atmak izin] 14242 236/let-gson-throw-istisna-yanlış-türleri) –

cevap

9

GSONgöre

Atmalar: json akışı sağlanan tipine göre serisi kaldırılan olamaz eğer 210 bir istisna zaten atılır JsonParseException - json tipi classOfT bir nesne için geçerli bir temsilidir değilse

Ama bir

try { 
    Room r = gson.fromJson(json, Room.class); 
} 
catch (JsonParseException e) { 
    throw new YourException(); 
} 
+0

Benim arayışımı düzenledim. Bunu test ettim ve işe yaramıyor. – pepuch

+0

Oda r = gson.fromJson (..); (r == null) yeni özel durum (..); – Jack

+1

Evet, haklısınız ama bu yanlış:/Dokümantasyon, bu yöntemlerin JsonParseException'ı atması gerektiğini söylüyor, ancak şunları değil:/Bildiğim gibi Boş doğrulama 'kötü bir modeldir. – pepuch

İlgili konular