简体   繁体   English

以json格式将数据从Java发送到javascript

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

I have some data 我有一些数据

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

I need to convert in JSON for javascript. 我需要将JSON转换为JavaScript。 The data must return key and value which I can display in a document. 数据必须返回可以在文档中显示的键和值。 I tried to use the method JSON.stringify and JSON.parse, but it converts in a string. 我尝试使用JSON.stringify和JSON.parse方法,但是它转换为字符串。

You can build and print your JSON by hand but you'll probably want to use SimpleJSON, Jackson 2 or GSON which will suit you better as the data gets more complex: 您可以手工构建和打印JSON,但您可能希望使用SimpleJSON,Jackson 2或GSON,随着数据变得越来越复杂,它们将更适合您:

SimpleJSON: https://github.com/fangyidong/json-simple , JAR SimpleJSON: https://github.com/fangyidong/json-simpleJAR

GSON: https://github.com/google/gson , JAR 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: MyRecord.java:

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

From Java you can receive stringified JSON and you can parse it using JSON.parse() on javascript side to have it as a regular object. 从Java中,您可以接收stringified JSON并且可以在javascript端使用JSON.parse()对其进行解析,以将其作为常规对象。

  1. Using Gson to convert Java object to JSON. 使用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 Side JavaScript端

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM