6

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
  • 18,131
  • 26
  • 91
  • 148

2 Answers2

11

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
  • 571
  • 4
  • 15
7

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
  • 60,548
  • 8
  • 97
  • 143