How to convert JSON string to custom object?

java, json

Solution

You can implement a static method in `MyClass` that takes `JSONObject` as a parameter and returns a `MyClass` instance. For example:

public static MyClass convertFromJSONToMyClass(JSONObject json) {
    if (json == null) {
        return null;
    }
    MyClass result = new MyClass();
    result.username = (String) json.get("username");
    result.name = (String) json.get("name");
    return result;
}

Problem

I've string like this (just ) ``` "{\"username":\"stack\",\"over":\"flow\"}" ``` I'd successfully converted this string to JSON with ``` JSONObject object = new JSONObject("{\"username":\"stack\",\"over":\"flow\"}"); ``` I've a class ``` public class MyClass { public String username; public String over; } ``` How can I convert JSONObject into my custom MyClass object?

Original source

Related problems