7

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?

sensorario
  • 20,262
  • 30
  • 97
  • 159

2 Answers2

12

you need Gson:

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

also what might come handy in future projects for you: Json2Pojo Class generator

Goran Štuc
  • 581
  • 4
  • 15
8

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;
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147