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?
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.
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).
string str=obj. Tostring(); Above code is working.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With