Is there an easy way to map data from JSON to fields of my class by means of android APIs?
JSON:
{ email: 'email', password: 'pass' }
My class:
class Credentials
{
string email;
string password;
}
We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.
POJO stands for Plain Old Java Object. It is an ordinary Java object, not bound by any special restriction other than those forced by the Java Language Specification and not requiring any classpath. POJOs are used for increasing the readability and re-usability of a program. JSON To POJO. Input (Editable)
First, we need to convert the JSON string into a JSON Object, using JSONObject class. Also, note that “pageInfo” is a JSON Object, so we use the getJSONObject method. Likewise, “posts” is a JSON Array, so we need to use the getJSONArray method.
Use Jackson. Much more convenient (and if performance matters, faster) than using bundled org.json classes and custom code:
Credentials c = new ObjectMapper().readValue(jsonString, Credentials.class);
(just note that fields of Credentials need to be 'public' to be discovered; or need to have setter methods)
You could use GSON.
Use the org.json-Package.
JSONObject x = new JSONObject(jsonString);
Credentials c = new Credentials();
c.email = x.getString("email");
c.password = x.getString("password");
Its also part of the android runtime, so you dont need any external package.
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