Search code examples
javajsonserializationorg.json

How do you deserialize JSON in java, using JSON.org


I am using "org.json" for JSON. I am able to serialize any class into a JSON string, using JSONObject. However, I'm not sure how to go the other way. How does one Deserialize a JSON string back into a class instance?

This code works to serialize it. I use JSONObject, and I provide a list of field names as a second argument to the constructor - User.JSONFieldMap().

    int randomValue = rnd.nextInt(10000);
    String userName = "JavaUnitTest_" + randomValue;
    User newUser = new User();
    newUser.UserName = userName;
    newUser.DisplayName = "Java Unit Test";
    newUser.EmailAddress = userName + "@SomeDomainName.com";
    JSONObject jsonUser = new JSONObject(newUser, User.JSONFieldMap());
    String userStringified = jsonUser.toString();

I'm not sure how, or if it is possible to be able to do something like this:

    User myUser = MagicJSONDeserializer.DeserializeIt("{ some JSON string}");

Thanks for any help, I come from a .net/C#/Microsoft background, so Java is very new to me.


Solution

  • That library does not provide such functionality directly. You can use any of hundreds of other Java JSON libraries that do, such as Gson, Jackson, or flexjson.

    The indirect way of doing it would be to retrieve each value from the JSON and perform custom deserialization on that value before assigning it to an object field.