There are several ways to create JSON in Android:
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();
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);
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.
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
Asked: 2023-05-02 13:34:34 +0000
Seen: 9 times
Last updated: May 02 '23
How can JSON be decoded while using a universal interface as a field?
How can I convert a `dataframe` from Polars to `serde_json::Value` using serialization?
In RobotFramework, can multiple key-value pairs in JSON format be obtained and saved to a JSON file?
How can JSON objects with dynamic keys be extracted in Athena/Presto?
What is the method for parsing a single JSON object in Android?
"What is the method of utilizing CURL POST with a payload in Json format?"
How can a JSON serialize detect a potential object cycle in .NET MAUI?
How can struct be utilized in the Go language to parse nested JSON?