簡體   English   中英

以json格式將數據從Java發送到javascript

[英]Send data from java to javascript in format json

我有一些數據

@Override
     public String toString() {
          return
               "{" +
                    "id:" + id +
                    ", title:'" + title + '\'' +
               "}";
     }

我需要將JSON轉換為JavaScript。 數據必須返回可以在文檔中顯示的鍵和值。 我嘗試使用JSON.stringify和JSON.parse方法,但是它轉換為字符串。

您可以手工構建和打印JSON,但您可能希望使用SimpleJSON,Jackson 2或GSON,隨着數據變得越來越復雜,它們將更適合您:

SimpleJSON: https://github.com/fangyidong/json-simpleJAR

GSON: https://github.com/google/gsonJAR

//Simple JSON
import org.json.simple.JSONObject;

//GSON
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class JSONExamples {

    public static void main(String[] args) {
        String id = "123";
        String title = "Very Important Record";


        //Simple JSON
        JSONObject obj = new JSONObject();
        obj.put("id", id);
        obj.put("title", title);
        System.out.println(obj);


        //GSON
        MyRecord myImportantRecord = new MyRecord(id, title);
        Gson gson = new GsonBuilder().create();
        gson.toJson(myImportantRecord, System.out);

    }

}

MyRecord.java:

public class MyRecord {
    private String id;
    private String title;
    MyRecord(String id, String title) {
        this.id=id;
        this.title=title;
    }
}

從Java中,您可以接收stringified JSON並且可以在javascript端使用JSON.parse()對其進行解析,以將其作為常規對象。

  1. 使用Gson將Java對象轉換為JSON。

     Gson gson = new Gson(); Staff obj = new Staff(); //Java object to JSON, and assign to a String String jsonInString = gson.toJson(obj); 
  2. JavaScript端

     var myObj = JSON.parse(this.responseText); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM