0

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.

4

2 回答 2

0

您可以从 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);
    
于 2018-07-11T15:25:42.150 回答
0

您可以手动构建和打印 JSON,但您可能希望使用 SimpleJSON、Jackson 2 或 GS​​ON,随着数据变得更加复杂,它们会更适合您:

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);

    }

}

我的记录.java:

public class MyRecord {
    private String id;
    private String title;
    MyRecord(String id, String title) {
        this.id=id;
        this.title=title;
    }
}
于 2018-07-11T15:24:10.407 回答