How to convert a JSON string to a custom object?

I have a line like this (simple)

"{\"username":\"stack\",\"over":\"flow\"}"

I successfully converted this string to JSON using

JSONObject object = new JSONObject("{\"username":\"stack\",\"over":\"flow\"}");

I have a class

public class MyClass
{
    public String username;
    public String over;
}

How to convert a JSONObject to my custom MyClass object?

+4
source share
2 answers

You can implement a static method in MyClassthat takes JSONObjectas a parameter and returns an instance MyClass. 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;
}
+6
source

you need gson:

Gson gson = new Gson(); 
final MyClass myClass = gson.fromJson(jsonString, MyClass.class);

and what may come in handy in future projects for you: Json2Pojo class generator

+5
source

All Articles