我们如何用Java编码JSON对象?
甲的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", "nhooo");
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":"nhooo","Age":25,"Name":"Adithya"}例
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"}热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下