简体   繁体   中英

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. 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.

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:

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

GSON: https://github.com/google/gson , JAR

//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;
    }
}

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.

  1. Using Gson to convert Java object to 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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