13

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

4 Answers 4

14

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)

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

Comments

8

You could use GSON.

1 Comment

be aware of this issue with HTC phones: sites.google.com/site/gson/gson-on-android
6

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.

3 Comments

It is included indeed, but it does not exactly map data. It parses/writes JSON, and offers a simple node-based API. But it is Your code does doing mapping here.
I do it by making a constructor in the Credentials with the fields so I can do the same code in 2 lines instead. JSONObject x = new JSONObject(jsonString); Credentials c = new Credentials( x.getString("email"),x.getString("password"));
Use this => GSON. And this to create a POJO JSONSCHEMA2POJO.
0

I suppose you have more than one Credential u want to get...

with the org.json package you could use a JSONArray to get various values at the same time out of one JSON file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.