I planned to use simpleXML for my serialization tasks, but decided that I would try JSON to learn something new.
This is the code I use to try to serialize the ArrayList of a POJO test using Gson 1.7.1.
Note. I removed Reader / Writers for the line to simplify the code.
package test; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.google.gson.Gson; public class TestGsonSerialDeserialList { public static void main(String[] args) throws IOException{ Gson gson = new Gson();
Here is the result I get:
[{"objectID":1,"i1":12345,"name":"abcdefg","s":["a","b","c"]},{"objectID":2,"i1":12345,"name":"abcdefg","s":["a","b","c"]}] java.lang.Object@5c74c3aa java.lang.Object@75d9fd51
To my newcomers, this looks right. Only, the list of DeSerialized objects contains the base objects, and TestObject I is not serialized. Can someone explain to me what, if anything, I can do to make this work?
EDIT:
Fixed for validation: thanks ColinD
package test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class TestGsonSerialDeserialList { public static void main(String[] args) throws IOException{ System.out.println("--- Serialize / Deserialize Started ---"); String fileName = "json\\testList.json"; Gson gson = new Gson(); Type listOfTestObject = new TypeToken<List<TestObject>>(){}.getType();
exit:
--- Serialize / Deserialize Started --- ID
EDIT2:
I honestly donβt know why, but when I replaced the simple String [] built into my TestObject with an ArrayList, it started to serialize correctly.
--- Serialize / Deserialize Started --- ID
java json arraylist gson serialization
RogueDeus Apr 28 2018-11-11T00: 00Z
source share