简体   繁体   English

如何在 servlet 中使用 GSON 解析此 JSON 字符串

[英]How do I parse this JSON string using GSON in servlet

How can I parse this JSON string to create collection object in servlet如何解析此 JSON 字符串以在 servlet 中创建集合对象

{"title":["1","2"],"amount":["1","3"]}

inner class in my servlet我的 servlet 中的内部类

public class Data {
    private List<String> title;
    private List<String> amount;
  //getters and setters
}

parsing json解析json

Gson gson = new Gson();
String param=request.getParameter("info");
Data data = gson.fromJson(param, Data.class);
List<String> a=data.getTitle();
 if(a==null){p("a null");}else{p("a not null");} //here a is null, prints "a null"

here is the jsfiddle of how I am creating the json string http://jsfiddle.net/testtracker/XDNLp/这是我如何创建 json 字符串的 jsfiddle http://jsfiddle.net/testtracker/XDNLp/

client side in form submit function表单提交功能中的客户端

var dataString=JSON.stringify($(this).serializeObject());
$.ajax({
    type: "POST",
    url: URL,
    data: {"info":JSON.stringify($(this).serializeObject())},
    success: function(data){

    }
  });

This is what I have till now.这就是我迄今为止所拥有的。 am I on correct way?我在正确的路上吗? what next should I do to System.print them?接下来我应该怎么做 System.print 它们?

When I am unable to solve something, I write the smallest possible program to verify my understanding is correct.当我无法解决某些问题时,我会编写尽可能小的程序来验证我的理解是否正确。 In your case, I came up with this:在你的情况下,我想出了这个:

import java.util.List;
import com.google.gson.Gson;
public class GsonTest {

public static class Data {
    private List<String> title;
    public List<String> getTitle() {return title;}
    public Data() {}
}

public static void main (String [] args) {
    Gson gson = new Gson();
    Data data = gson.fromJson("{\"title\":[\"1\",\"2\"]}", Data.class);
    System.out.println(data.getTitle());
} 
}

Compiled, and ran, and it outputs:编译并运行,它输出:

["1", "2"]

So I still believe that the input that the servlet receives, is not correct (or you have not provided an accurate description of your existing code).所以我仍然认为 servlet 接收的输入不正确(或者您没有提供对现有代码的准确描述)。 Please compare the example above, against your real code.请将上面的示例与您的真实代码进行比较。

try尝试

public class Data {
    private ArrayList<String> title;
    private ArrayList<String> amount;
  //getters and setters
}

List is a abstract class (So GSON doesn't know how to create it) List 是一个抽象类(所以 GSON 不知道如何创建它)

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

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