首頁  >  文章  >  Java  >  我們如何在Java中對JSON物件進行編碼?

我們如何在Java中對JSON物件進行編碼?

WBOY
WBOY轉載
2023-09-11 14:53:031415瀏覽

我們如何在Java中對JSON物件進行編碼?

JSONObjectjava.util.HashMap的子類,其中不提供順序。我們也可以在 JSONValue.toJSONString(map) 方法的幫助下使用元素的嚴格排序,也就是透過 java.util.LinkedHashMap 的實作。 p>

我們可以在下面的兩個範例中對 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"}

以上是我們如何在Java中對JSON物件進行編碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除