Home> Java> javaTutorial> body text

How to convert Map to JSON object using JSON-lib API in Java?

WBOY
Release: 2023-08-29 16:37:02
forward
797 people have browsed it

如何使用Java中的JSON-lib API将Map转换为JSON对象?

JSONObjectis an unordered collection ofname/valuepairs, whileMapis a mapping key Objects to values. The map cannot containduplicatekeys, and each key can be mapped to at most one value. We need to use theJSON-liblibrary toserializeanddeserializethe map in JSON format. Initially, we can create a POJO class and pass the instance as parameter to theput()method of theMapclass and finally add this map instance to theaccumulateAll JSONObject Methods.

Syntax

public void accumulateAll(Map map)
Copy after login

In the following example, we can convert Map to JSON object.

Example

import java.util.*; import net.sf.json.JSONObject; public class ConvertMapToJSONObjectTest { public static void main(String[] args)throws Exception { JSONObject jsonObject = new JSONObject(); Map employees = new HashMap(); employees.put(1, new Employee("Adithya", "Jai", 30)); employees.put(2, new Employee("Vamsi", "Krishna", 28)); employees.put(3, new Employee("Chaitanya", "Sai", 30)); jsonObject.accumulateAll(employees); System.out.println(jsonObject.toString(3)); // pretty print JSON } public static class Employee { private String firstName, lastName; private int age; public Employee(String firstName, String lastName, int age) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } } }
Copy after login

Output

{ "1": { "firstName": "Adithya", "lastName": "Jai", "age": 30 }, "2": { "firstName": "Vamsi", "lastName": "Krishna", "age": 28 }, "3": { "firstName": "Chaitanya", "lastName": "Sai", "age": 30 } }
Copy after login

The above is the detailed content of How to convert Map to JSON object using JSON-lib API in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!