Home > Java > javaTutorial > How do we encode JSON objects in Java?

How do we encode JSON objects in Java?

WBOY
Release: 2023-09-11 14:53:03
forward
1474 people have browsed it

How do we encode JSON objects in Java?

JSONObject is a subclass of java.util.HashMap which does not provide ordering. We can also use strict ordering of elements with the help of the JSONValue.toJSONString(map) method, i.e. through the implementation of java.util.LinkedHashMap. p>

We can encode JSON objects in the two examples below.

Example

import java.util.*;
import org.json.simple.JSONObject;
public class JSONEncodingTest {
   public static void main(String[] args) {
      Map<Object, Object> dataMap = new HashMap<Object, Object>();
      dataMap.put("Name", "Adithya");
      dataMap.put("Age", new Integer(25));
      dataMap.put("Salary", new Double(25000.00));
      dataMap.put("Employee Id", new Integer(115));
      dataMap.put("Company", "TutorialsPoint");
      JSONObject jsonObj = new JSONObject(dataMap);
      System.out.print("Encoding a JSON object: ");
      System.out.print(jsonObj);
   }
}
Copy after login

Output

Encoding a JSON object: {"Salary":25000.0,"Employee id":115,"Company":"TutorialsPoint","Age":25,"Name":"Adithya"}
Copy after login

##Example

import java.io.*;
import org.json.simple.*;
public class JSONEncodingTest1 {
   public static void main(String[] args) throws IOException {
      JSONObject obj = new JSONObject();
      obj.put("Name", "Jai");
      obj.put("Mobile_Number", new Integer(995998480));
      obj.put("Bank_Balance", new Double(50000.00));
      obj.put("Is_A_SelfEmployee", new Boolean(false));
      StringWriter out = new StringWriter();
      obj.writeJSONString(out);
      String jsonText = out.toString();
      System.out.print(jsonText);
   }
}
Copy after login

Output

{"Is_A_SelfEmployee":false,"Bank_Balance":50000.0,"Mobile_Number":995998480,"Name":"Jai"}
Copy after login

The above is the detailed content of How do we encode JSON objects 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template