Custom Deserializer GSON
I have been stumped on this topic for 2 days now, and cant seem to find what I need.
I have a class as follows:
public class myClass {
private String name;
private ArrayList<String> arr1;
private ArrayList<String> arr2;
}
I am posting json via jQuery ajax to a jsp file that needs to fill an array list of myClass for further processing later.
[{"name":"myName","arr1":["foo","bar","blahh"],"arr2":["foo","bar","blahh"]},
{"name":"myName2","arr1":["foo","bar","blahh"],"arr2":["foo","bar","blahh"]}]
I tried to make a custom deserializer, but all of my attempts have been in vain.
This is my current function: json = request.getParameter("myStuff");
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<myClass>>() {}.getType();
ArrayList<myClass> myClassList= new Gson().fromJson(json, listType);
开发者_开发知识库
Thanks to anyone who can help.
UPDATE: sorry, I forgot to clearly state what I am asking.
I have 2 questions that are related:1. Do I need to use a deserializer?2. If yes, what is wrong with the one I have now?The code and JSON you posted serializes and deserializes as expected for me, without any custom deserialization. I don't see anything wrong.
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Foo
{
public static void main(String[] args) throws Exception
{
Type listType = new TypeToken<ArrayList<myClass>>() {}.getType();
Gson gson = new Gson();
ArrayList<myClass> myClassList= new Gson().fromJson(new FileReader("input.json"), listType);
System.out.println(gson.toJson(myClassList));
}
}
class myClass
{
private String name;
private ArrayList<String> arr1;
private ArrayList<String> arr2;
}
Is this not what you're trying to achieve? Are you sure that the value of json
received from request.getParameter("myStuff")
is what you said it is?
精彩评论