Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON string to custom object? [duplicate]

Tags:

java

json

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?

like image 463
sensorario Avatar asked Nov 25 '13 13:11

sensorario


People also ask

How to deserialize JSON string to object in C#?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

Can JSON array have duplicate keys?

The short answer: Yes but is not recommended. The long answer: It depends on what you call valid... [ECMA-404][1] "The JSON Data Interchange Syntax" doesn't say anything about duplicated names (keys).

How to Convert string to object type in C#?

string str=obj. Tostring(); Above code is working.


2 Answers

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

like image 181
Goran Štuc Avatar answered Sep 20 '22 10:09

Goran Štuc


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;
}
like image 20
Konstantin Yovkov Avatar answered Sep 22 '22 10:09

Konstantin Yovkov