1

Can you recommend on a Json Deserializer that can deserialize into existing object (merge 2 objects)?
When the user submit a form I want to save that into the db this way:

this is the json from the client:

{"affiliateId":1,"name":"First Affiliate","email":"email@gmail.com","user.userName":"test","user.password":"pass-hashed","employee.employeeId":1}


Affiliate affiliateFromDb = affiliateApi.getFromDbById(1);

SomeDeserialization json = new SomeDeserialization();
affiliateFromDb = json.fromJson(affiliateFromJson  , affiliateFromDb );//affiliateFromDb = target bean

Meaning that I want the affiliateFromJson to be interpolated into affiliateFromDb.
And than I will call

 affiliateApi.save(affiliateFromDb);

Note that the json contains deep deserialize, user.userName

Thanks

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
fatnjazzy
  • 6,070
  • 12
  • 57
  • 83

2 Answers2

0

Use Gson! In particular, see the Object Examples.

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);   

The only catch here — but you will have this same problem with any other JSON (de)serializer — is the nonstandard "deep" object format you want to work with. You would have to use something like this instead:

{"affiliateId":1,"name":"First Affiliate","email":"email@gmail.com","user": {"userName":"test","password":"pass-hashed"},"employee.employeeId":1}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Thanks, but where is the merge here? I want to merge the object with an existing object. see my code again mayby, Thanks – fatnjazzy Apr 19 '11 at 19:40
  • I don't think you're going to find a JSON library that does this for you. Write a custom method on the `Affiliate` object, something like `Affiliate#mergeWith(Affiliate other)`. – Matt Ball Apr 19 '11 at 19:51
0

http://www.json.org/javadoc/org/json/JSONObject.html

JSONObject jsonResponse = new JSONObject(responseString);
Pim Reijersen
  • 1,123
  • 9
  • 33
  • Thanks, but where is the merge here? I want to merge the object with an existing object. see my code again mayby, Thanks – fatnjazzy Apr 19 '11 at 19:40