这是JSON字符串1
{"title":["1","2"], "amount":["1","2"]}
这是JSON字符串2
{"title":"", "amount":""}
当我在表单中输入值时创建了字符串1,而在我不创建时创建了字符串2, 我想知道字符串是格式1,标题是数组[“1”,“2”]还是格式2,标题只是servlet中服务器端的字符串“”,然后我解析它。有没有办法这样做?
这是我之前的问题, How do I parse this JSON string using GSON in servlet
已经解决,但正如你所看到的,我有类Data,其实例变量类型为ArrayList,所以当我用这行解析它时
Data data = gson.fromJson(param, Data.class);
它抛出异常
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 24
因为我已经声明了ArrayList,它只希望json中的数组解析它而没有任何异常....但是当我不在表单中输入值时它不会创建json字符串
{"title":[], "amount":[]}
而是像这样创造
{"title":'', "amount":''}
其中string为value,导致解析抛出异常
答案 0 :(得分:3)
也有这个问题,这就是我如何解决它
在您的Data对象中
public class Data {
// This is a generic object whose type is determined when used by GSON
private Object title;
// get the type of object and return as string
public String getTitleObjType() {
String objType = title.getClass().toString();
return objType;
}
// used if the object is an ArrayList, convert into an ArrayList<Object>
public ArrayList<String> getTitleArrayList() {
// Turn the Object into an arraylist
@SuppressWarnings("unchecked") // This is to counter the fact that the cast is not type safe
ArrayList<String> titleArrayList = (ArrayList<String>) title;
return titleArrayList;
}
// used if the object is not an array
public String getTitleStr() {
return title.toString();
}
}
当GSON构建它将创建的对象时,它们中的每一个都是String或ArrayList
然后,当您想要使用这些对象时,请测试它们是什么
ArrayList<String> titleValArrayList = new ArrayList<String>();
String titleValStr = "";
if(getTitleObjType.equals("class java.util.ArrayList")) {
titleValArrayList = getTitleArrayList();
//do whatever you like
}
else if(getTitleObjType.equals("class java.util.String")) {
titleValStr = getsTitleStr();
//do whatever you like
}
答案 1 :(得分:2)
检查Google GSON它允许您解析JSON服务器端。
它是这样的:
String jsonString = request.getParameter("jsonParemeter");
Gson gson = new Gson();
Map fromJsonMap = gson.fromJson(jsonString, HashMap.class);
Object object = fromJsonMap.get("title");
if (object instanceof Collection) {
// then is it's your array
}
else {
// it's not
}
例如,如果我运行以下示例代码:
String json1 = "{\"title\":[\"1\",\"2\"], \"amount\":[\"1\",\"2\"]}";
String json2 = "{\"title\":\"\", \"amount\":\"\"}";
Gson gson = new Gson();
HashMap map = gson.fromJson(json1, HashMap.class);
HashMap map2 = gson.fromJson(json2, HashMap.class);
System.out.println(map);
System.out.println(map2);
System.out.println(map.get("amount").getClass());
System.out.println(map2.get("amount").getClass());
我得到了输出:
{amount=[1, 2], title=[1, 2]}
{amount=, title=}
class java.util.ArrayList
class java.lang.String
如果我理解正确,我认为它适合你100%
<强>更新强>
由于您尝试将JSON字符串直接反序列化为Data对象,因此如果要继续执行直接反序列化,则必须使用custom deserialization mechanism