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?

1
  • 2
    Look into Jackson or Gson, they both handle this sort of thing. Commented Nov 25, 2013 at 13:24

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

+1 Note: Gson is great for simple cases. If you need more control, have a look at Jackson.
@Goran Štuc One doubt, what is this GSON, is that better than JSON Object
Gson is an API which you can obtain here: code.google.com/p/google-gson
9

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;
}

1 Comment

Is there any way to convert the object using JSONObject? without modifying the class

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.