[英]How to format JSON string of data to send from WebView to 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-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;
}
}
从Java中,您可以接收stringified JSON
并且可以在javascript端使用JSON.parse()
对其进行解析,以将其作为常规对象。
使用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);
JavaScript端
var myObj = JSON.parse(this.responseText);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.