Ask Your Question
4

How can JSON be created in Android?

asked 2023-05-02 13:34:34 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-02 13:49:02 +0000

huitzilopochtli gravatar image

There are several ways to create JSON in Android:

  1. Using JSONObject and JSONArray classes:
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 30);

JSONArray jsonArray = new JSONArray();
jsonArray.put("red");
jsonArray.put("blue");
jsonArray.put("green");

jsonObject.put("colors", jsonArray);
String jsonString = jsonObject.toString();
  1. Using Gson library:
Gson gson = new Gson();

// Convert an object to JSON
Person person = new Person("John", 30);
String jsonString = gson.toJson(person);

// Convert a JSON string to an object
String jsonInput = "{\"name\":\"John\",\"age\":30}";
Person person = gson.fromJson(jsonInput, Person.class);
  1. Using Jackson library:
ObjectMapper mapper = new ObjectMapper();

// Convert an object to JSON
Person person = new Person("John", 30);
String jsonString = mapper.writeValueAsString(person);

// Convert a JSON string to an object
String jsonInput = "{\"name\":\"John\",\"age\":30}";
Person person = mapper.readValue(jsonInput, Person.class);

Note: In all the above examples, Person is a custom class that has name and age fields.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-02 13:34:34 +0000

Seen: 9 times

Last updated: May 02 '23