繁体   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