How do I parse this JSON string using GSON in servlet

妖精的绣舞 提交于 2019-12-12 08:16:29

问题


How can I parse this JSON string to create collection object in servlet

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

inner class in my servlet

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

parsing 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/

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?


回答1:


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). Please compare the example above, against your real code.




回答2:


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)



来源:https://stackoverflow.com/questions/13648273/how-do-i-parse-this-json-string-using-gson-in-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!