繁体   English   中英

包含ArrayList和HashMap的JSON

[英]JSON containing ArrayList and HashMap

我的servlet有一个ArrayListHashMap对象,我想通过AJAX发送到我的jsp。 我该怎么做,然后在将它们作为javascript responseText获取后,如何将它们分开? (不能使用jQuery)

ArrayList al = new ArrayList();
String json1= new Gson().toJson(al);
HashMap hm = new HashMap();
String json2= new Gson().toJson(hm);

到目前为止我所做的

ServletOutputStream os = res.getOutputStream();
String json = "[" + json1 + "," + json2 + "]";
System.out.println(json);
os.write(json.toString().getBytes());
flushCloseOutputStream(os);
res.setStatus(HttpServletResponse.SC_OK);

然后在jsp端

var jsonResponse = JSON.parse(this.responseText);
var workDesc = jsonResponse[1];
var thirdPartyData = jsonResponse[0];

我的问题是,这是发送回复的正确方法吗?

GSON将解决问题。 一个简单的例子:

import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;

class App {

    private static final Type hashMapStringApp = new TypeToken<HashMap<String,App>>(){}.getType();

    private String attribute;

    public App(String attribute) {
        this.attribute = attribute;
    }

    public static void main(String[] args) {
        Gson gson = new Gson(); 

        // Complex object to JSON
        HashMap<String, App> map = new HashMap<>();
        map.put("1", new App("Attr1"));
        map.put("2", new App("Attr2"));
        String json = gson.toJson(map);
        System.out.println(json);

        // JSON to complex object
        HashMap<String, App> fromJson = gson.fromJson(json, hashMapStringApp);
        System.out.println(fromJson.get("2").getAttribute());
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    };

    public String getAttribute(){
        return this.attribute;
    }
}

Maven的依赖:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.2</version>
</dependency>

暂无
暂无

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

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