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"} 예시
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"}