Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to Java class

Tags:

java

json

android

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;
}
like image 901
Eugene Avatar asked Jan 03 '11 12:01

Eugene


People also ask

Can you convert JSON to Java?

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.

What is JSON POJO?

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)

How do you parse a JSON object in Java?

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.


3 Answers

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)

like image 170
StaxMan Avatar answered Oct 21 '22 12:10

StaxMan


You could use GSON.

like image 28
Valentin Rocher Avatar answered Oct 21 '22 12:10

Valentin Rocher


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.

like image 28
KingCrunch Avatar answered Oct 21 '22 14:10

KingCrunch