如何在 Java 中编码 JSON 对象?
javajsonobject oriented programmingprogramming更新于 2025/7/1 7:08:17
JSONObject 是 java.util.HashMap 的子类,其中没有提供任何顺序。我们还可以借助 JSONValue.toJSONString(map) 方法(即通过实现 java.util.LinkedHashMap)使用元素的严格排序。
我们可以在以下两个示例中编码 JSON 对象。
示例
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);
}
}
输出
Encoding a JSON object: {"Salary":25000.0,"Employee id":115,"Company":"TutorialsPoint","Age":25,"Name":"Adithya"}
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);
}
}
输出
{"Is_A_SelfEmployee":false,"Bank_Balance":50000.0,"Mobile_Number":995998480,"Name":"Jai"}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

