In Java I have object of this kind Map<Member, Map<CustomerVO, Set<Vehicle>>> and one other List<DeviceOrder> I wanted to convert this to json, I tried with Gson but it is throwing error as "Forgot to register a type adapter?"
can someone please help how I do proceed, if not gson what would be other way to convert.
The above error was when I tried this way
List<DeviceOrder> devLst;
Gson gson = new Gson();
String jsonStr = gson.toJson(devLst);
for the other one as
Map<Member, Map<CustomerVO, Set<Vehicle>>> map;
Gson gson = new Gson();
String jsonStr = gson.toJson(map);
Please let me know what am I doing wrong. Later I want to pass this to jsp to display.
UPDATE:
Even tried this way as well, but no use.
Gson gson = new Gson();
Type type = new TypeToken<List<DeviceOrder>>(){}.getType();
String jsonstr = gson.toJson(devLst, type);
You may try out the standard implementation of the Java API for JSON processing which is part of J2EE.
For your List<DeviceOrder> devLst, define the bean:
public class DeviceOrder implements Serializable {
private static final long serialVersionUID = 893438341L;
public DeviceOrder() {
}
public DeviceOrder(int id, String desc, Date date) {
this.id = id;
this.desc = desc;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((desc == null) ? 0 : desc.hashCode());
result = prime * result + id;
return result;
}
private int id;
private String desc;
private Date date;
}
And then use:
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<DeviceOrder> devLst = new ArrayList<DeviceOrder>() {
{
add(new DeviceOrder(1, "order 1", sdf.parse("2010-05-01")));
add(new DeviceOrder(2, "order 2", sdf.parse("2010-06-01")));
add(new DeviceOrder(3, "order 3", sdf.parse("2010-07-01")));
}
};
DeviceOrder[] devArr = devLst.toArray(new DeviceOrder[devLst.size()]);
JsonArrayBuilder devArrBuilder = Json.createArrayBuilder();
for (DeviceOrder devOrder : devArr) {
JsonObjectBuilder jsonObject = Json.createObjectBuilder()
.add("id", devOrder.getId())
.add("desc", devOrder.getDesc())
.add("date", sdf.format(devOrder.getDate()));
devArrBuilder.add(jsonObject);
}
JsonArray jsonArray = devArrBuilder.build();
Map<String, Object> prop = new HashMap<String, Object>() {
{
put(JsonGenerator.PRETTY_PRINTING, true);
}
};
JsonWriter jsonWriter = Json.createWriterFactory(prop).createWriter(System.out);
jsonWriter.writeArray(jsonArray);
jsonWriter.close();
The output should be:
[
{
"id":1,
"desc":"order 1",
"date":"2010-05-01"
},
{
"id":2,
"desc":"order 2",
"date":"2010-06-01"
},
{
"id":3,
"desc":"order 3",
"date":"2010-07-01"
}
]
Your Map<Member, Map<CustomerVO, Set<Vehicle>>> map can be reduced to a List and JSONed in a similar fashion.
Related
How to validate each of the names, ages and descriptions irrespective of json array index? It will kind of search that we need to validate on the basis of name, age and description with age is matching or not.
[
{
"Name": "Shobit",
"transactionDate": 1623049638000,
"age": "18",
"description": "My item for new collection addition into system with age 18"
},
{
"Name": "Neha",
"transactionDate": 1623049877000,
"age": "20",
"description": "My item for new collection addition into system with age 20"
}
]
You can convert your data to JSONArray and check each item as a JSONObject for example
JSONArray array = new JSONArray(data);
for(int i = 0; i < array.length() ; i++) {
JSONObject user = array.getJSONObject(i);
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
}
Or move the validation to another method for example
JSONArray array = new JSONArray(data);
for(int i = 0; i < array.length() ; i++) {
JSONObject user = array.getJSONObject(i);
boolean isValidInfo = isValidateUser(user);
}
Validation method
public boolean isValidateUser(JSONObject user) {
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
}
For java you can use the library "org.json"
Add in your pom.xml dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
Now you can use the next solution with java 8 :
JSONArray jsonArray = new JSONArray(yourJsonArray);
IntStream.range(0, jsonArray.length()).forEachOrdered(index -> {
// below the solution #AmrDeveloper
JSONObject user = jsonArray.getJSONObject(index);
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
});
OR USE other libraries.
Example with Jackson
Add dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.2</version>
</dependency>
Create POJO:
public class User {
private String name;
private Long transactionDate;
private Integer age;
private String description;
public User(String name, Long transactionDate, Integer age, String description) {
this.name = name;
this.transactionDate = transactionDate;
this.age = age;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(Long transactionDate) {
this.transactionDate = transactionDate;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Create method:
public <T> Optional<List<T>> buildListObjectsFromJson(String jsonObjectsList, Class<T> clazz) {
LOGGER.info("Try to build list objects from json....");
try {
ObjectMapper objectMapper = new ObjectMapper();
List<T> objectsList = objectMapper
.readValue(jsonObjectsList, objectMapper.getTypeFactory()
.constructCollectionType(ArrayList.class, clazz));
LOGGER.info("Objects list created successfully! List size = {}", objectsList.size());
return Optional.of(objectsList);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Can't build List objects by json: {}", jsonObjectsList);
}
return Optional.empty();
}
And create use next example:
List<User> users = buildListObjectsFromJson(yourJsonArray, User.class).orElse(new ArrayList<>());
This way you can work with this data as a collection.
This is one in a row of deserialization questions but I've read them all and can't figure out the solution for my problem.
I need to get all the "entery"->"content" ->$t and "entery"->"title"->"$t" but in CategoryDeserializer() I get JsonArray that is NULL. I've pointed to that part of the code with "<====".
Error message:
Attempt to invoke interface method 'java.util.Iterator
java.util.List.iterator()' on a null object reference
I have JSON that looks something like this:
{ "feed":{
"id":{ ... },
"author":[ ... ],
"entry":[
{
"id":{ },
"updated":{ },
"category":[ ],
"title":{
"type":"text",
"$t":"A1 },
"content":{
"type":"text",
"$t":"test"
},
"link":[ ]
},
{ ... },
{ ... },
{ ...},
]
}
}
This is part of my code where I try to deserialize "entery":
String json = response.body().toString();
Type listType = new TypeToken<List<Entry>>() {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(listType, new CategoryDeserializer()).create();
List<Entry> list = gson.fromJson(json, listType);
for (Entry entry : list) {
Log.i("MainActivity", "Content: " + entry.getContent());}
Where CategoryDeserializer() looks like this:
public class CategoryDeserializer implements JsonDeserializer<List<Entry>> {
public List<Entry> deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
JsonArray entry = je.getAsJsonObject().getAsJsonArray("entry"); //<==== here I get that entry is null but je has a value
ArrayList<Entry> myList = new ArrayList<Entry>();
for (JsonElement e : entry) {
myList.add((Entry) jdc.deserialize(e, Entry.class));
}
return myList;}
And my Entry class:
public class Entry {
private Id_ id;
private Updated_ updated;
private List<Category_> category = null;
private Title_ title;
private Content content;
private List<Link_> link = null;
//getters and setters
public Id_ getId() {
return id;
}
public void setId(Id_ id) {
this.id = id;
}
public Updated_ getUpdated() {
return updated;
}
public void setUpdated(Updated_ updated) {
this.updated = updated;
}
public List<Category_> getCategory() {
return category;
}
public void setCategory(List<Category_> category) {
this.category = category;
}
public Title_ getTitle() {
return title;
}
public void setTitle(Title_ title) {
this.title = title;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
public List<Link_> getLink() {
return link;
}
public void setLink(List<Link_> link) {
this.link = link;
}
}
Edit: I have declaration and instantiation.
I was complicating things that were not complicated. All I had to do was this:
String json = response.body().toString();
Gson mGson = new Gson();
//where Example is the root of JSON
Example rsp = mGson.fromJson(json, Example.class);
//Entry is the list I needed to access
List <Entry> listOfEntrys= rsp.getFeed().getEntry();
//get value
Log.i("MainActivity", "listaEntrya " + listOfEntrys.get(0).getTitle().get$t());
Hello guys i need to output a json string like this, I use Java and Jackson.
{"x_axis": {"type": "datetime"},"series": [
{
"name": "Visitors per month",
"data": [
["2014-01", 71173],
["2014-02", 57624],
["2014-03", 64851],
["2014-04", 60486],
["2014-05", 60500],
["2014-06", 62908],
["2014-07", 64818],
["2014-08", 59961],
["2014-09", 58542],
["2014-10", 22050]
],
} ]}
But I tried everything but I get this, i hope you will understand.
{"series": [
{
"data": [
"{2016-02-12 09:00:00.0, 565}",
"{2016-02-12 09:00:00.0, 565}"
],
"name": "Calls per minute"
}],"x_axis": {
"type": "datetime"}}
UPDATE
The problem is I want to output the data like this
"data": [
["2014-01", 71173],
["2014-02", 57624],
["2014-03", 64851],
["2014-04", 60486],
["2014-05", 60500],
["2014-06", 62908],
["2014-07", 64818],
["2014-08", 59961],
["2014-09", 58542],
["2014-10", 22050]
]
And not like this
"data": [
"{2016-02-12, 565}",
"{2016-02-12, 565}"
]
My Method
public class DataItem
{
public String str;
public String count;
#Override
public String toString() {
return "{"+ str + ", " + count + "}"; // Dit roept de parser aan.
}
public DataItem(String Date, String count)
{
this.str = Date;
this.count = count;
}
}
public LineChart getaverageCallsPerMinuteAsLineChart() throws SQLException {
String query = "select date, averageCallsPerMinute from information where date between now() - INTERVAL 1 DAY and now()";
LineChart linechart = new LineChart();
X_Axis x_axis = new X_Axis("datetime");
linechart.setX_axis(x_axis);
ArrayList<Series> seriesArray = new ArrayList<>();
Series series = new Series();
series.setName("Calls per minute");
List<List<Object>> data = new ArrayList<>();
try {
conn = DBConnection.setDBConnection();
statement = conn.createStatement();
rs = statement.executeQuery(query);
while(rs.next()){
List<Object> dataItems;
String date = rs.getString(1);
String calls = rs.getString(2);
if(date != null || calls != null)
{
DataItem di = new DataItem(date, calls);
dataItems = new ArrayList<Object>(Arrays.asList(di));
data.add(dataItems);
}
}
}catch(Exception e){
System.out.println(e);
}finally{
rs.close();
conn.close();
}
series.setData(data);
seriesArray.add(series);
linechart.setSeries(seriesArray);
return linechart;
}
My classes
public class Series {
private String name;
private List<List<Object>> data;
public Series(){}
public Series(String name, List<List<Object>> data){
this.data = data;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<List<Object>> getData() {
return data;
}
public void setData(List<List<Object>> data) {
this.data = data;
}
}
public class X_Axis {
private String type;
public X_Axis(){}
public X_Axis(String type){
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class LineChart {
private X_Axis x_axis;
private ArrayList<Series> series;
public LineChart(){}
public LineChart(X_Axis x_axis, ArrayList<Series> series){
this.x_axis = x_axis;
this.series = series;
}
public X_Axis getX_axis() {
return x_axis;
}
public void setX_axis(X_Axis x_axis) {
this.x_axis = x_axis;
}
public ArrayList<Series> getSeries() {
return series;
}
public void setSeries(ArrayList<Series> series) {
this.series = series;
}
}
#GET
#Path("/CallsPerMinuteAsLineChart")
#Produces(MediaType.APPLICATION_JSON)
public LineChart CallsPerMinute() throws SQLException {
CompanyDB comp = new CompanyDB();
LineChart linechart = comp.getaverageCallsPerMinuteAsLineChart();
return linechart;
}
(I can't post comments yet)
I would say that your :
#Override
public String toString() {
return "{"+ str + ", " + count + "}"; // Dit roept de parser aan.
}
is creating the output with the format "{2016-02-12, 565}" instead of ["2014-01", 71173]. The second one, makes me think that they are 2 objects, a String and an Integer, not just one Object (your DataItem class) with 2 attributes and the toString() function overwritten. I am not very familiar with those libraries but I think you should somehow add to the JSON twice, first time the time and then the value.
Apart from that, I am checking the formating of the Date, I wil come back when I get something.
EDIT: To get the correct format of the Date I found this:
Date utilDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
utilDate = formatter.parse(date);
So I would just change the mask to "yyyy-MM"
I'm trying deserializes a JSONArray to List. To do it I'm trying use Gson but I can't understand why doesn't works and all values of JSON are null.
How could I do this ?
JSON
{ "result" : [
{ "Noticia" : {
"created" : "2015-08-20 19:58:49",
"descricao" : "tttttt",
"id" : "19",
"image" : null,
"titulo" : "ddddd",
"usuario" : "FERNANDO PAIVA"
} },
{ "Noticia" : {
"created" : "2015-08-20 19:59:57",
"descricao" : "hhhhhhhh",
"id" : "20",
"image" : "logo.png",
"titulo" : "TITULO DA NOTICIA",
"usuario" : "FERNANDO PAIVA"
} }
] }
Deserializes
List<Noticia> lista = new ArrayList<Noticia>();
Gson gson = new Gson();
JSONArray array = obj.getJSONArray("result");
Type listType = new TypeToken<List<Noticia>>() {}.getType();
lista = gson.fromJson(array.toString(), listType);
//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
Log.i("TITULO", n.getTitulo());
}
Class Noticia
public class Noticia implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String titulo;
private String descricao;
private String usuario;
private Date created;
private String image;
There are two problems with your code :
First is that you are using a getJsonArray() to get the array,
which isn't part of Gson library, you need to use
getAsJsonArray() method instead.
Second is that you are using array.toString() which isn't obvious
because for the fromJson method you need a jsonArray as
parameter and not String and that will cause you parse problems, just remove it.
And use the following code to convert your jsonArray to List<Noticia> :
Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);
And your whole code will be:
Gson gson = new Gson();
JSONArray array = obj.getAsJsonArray("result");
Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);
//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
Log.i("TITULO", n.getTitulo());
}
I think the problem could be something to do with toString() on JSONArray. But are you using obj.getAsJsonArray method?
Try this:
JSONArray arr = obj.getAsJsonArray("result");
Type listType = new TypeToken<List<Noticia>>() {
}.getType();
return new Gson().fromJson(arr , listType);
Noticia.java
public class Noticia {
private String created;
private String descricao;
private String id;
private String image;
private String titulo;
private String usuario;
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
#Override
public String toString() {
return "Noticia [created=" + created + ", descricao=" + descricao
+ ", id=" + id + ", image=" + image + ", titulo=" + titulo
+ ", usuario=" + usuario + "]";
}
}
Result.java
public class Result {
private Noticia Noticia;
public Noticia getNoticia() {
return Noticia;
}
public void setNoticia(Noticia noticia) {
Noticia = noticia;
}
#Override
public String toString() {
return "Result [Noticia=" + Noticia + "]";
}
}
Item.java
import java.util.List;
public class Item {
private List<Result> result;
public List<Result> getResult() {
return result;
}
public void setResult(List<Result> result) {
this.result = result;
}
#Override
public String toString() {
return "Item [result=" + result + "]";
}
}
Main.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Item;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
public static void main(String[] args) {
String j = "{\"result\":[{\"Noticia\":{\"created\":\"2015-08-20 19:58:49\",\"descricao\":\"tttttt\",\"id\":\"19\",\"image\":null,\"titulo\":\"ddddd\",\"usuario\":\"FERNANDO PAIVA\"}},{\"Noticia\":{\"created\":\"2015-08-20 19:59:57\",\"descricao\":\"hhhhhhhh\",\"id\":\"20\",\"image\":\"logo.png\",\"titulo\":\"TITULO DA NOTICIA\",\"usuario\":\"FERNANDO PAIVA\"}}]}";
Item r = gson.fromJson(j, Item.class);
System.out.println(r);
}
}
Final result
Item [result=[Result [Noticia=Noticia [created=2015-08-20 19:58:49, descricao=tttttt, id=19, image=null, titulo=ddddd, usuario=FERNANDO PAIVA]], Result [Noticia=Noticia [created=2015-08-20 19:59:57, descricao=hhhhhhhh, id=20, image=logo.png, titulo=TITULO DA NOTICIA, usuario=FERNANDO PAIVA]]]]
You parse json, that looks like
{ "result" : [
{
"created" : "2015-08-20 19:58:49",
"descricao" : "tttttt",
"id" : "19",
"image" : null,
"titulo" : "ddddd",
"usuario" : "FERNANDO PAIVA"
},
{
"created" : "2015-08-20 19:59:57",
"descricao" : "hhhhhhhh",
"id" : "20",
"image" : "logo.png",
"titulo" : "TITULO DA NOTICIA",
"usuario" : "FERNANDO PAIVA"
}
] }
You need to make another object Item and parse a list of them.
public class Item{
Noticia noticia;
}
Or you can interate through JSONArray, get field "noticia" from each then parse Noticia object from given JSONObject.
Kotlin Ex :
we getting response in form of JSONArry
call.enqueue(object : Callback<JsonArray> {
override fun onResponse(call: Call<JsonArray>, response: Response<JsonArray>) {
val list = response.body().toString()
val gson = Gson()
val obj: CitiesList? = gson.fromJson(list, CitiesList::class.java)
cityLiveData.value = obj!!
}
override fun onFailure(call: Call<JsonArray>, t: Throwable) {
}
})
Here CitiesList CitiesList::class.java is the ArrayList of Cities object
class CitiesList : ArrayList<CitiesListItem>()
Before using GSON add dependancey in Gradle
dependencies {
implementation 'com.google.code.gson:gson:2.8.8'
}
I have to generate JSON in below sample format:
[
{ "roleName" : "Parent Folder", "folderId" : "role1", "expanded" : true,
"children" :
[
{ "roleName" : "subUser1 non-openable folder", "folderId" : "role11","fileicon" : true },
{ "roleName" : "subUser2", "folderId" : "role12", "expanded" : true,
"children" :
[
{ "roleName" : "subUser2-1", "folderId" : "role121", "expanded" : true, "children" :
[
{ "roleName" : "subUser2-1-1 folder ico", "folderId" : "role1211" },
{ "roleName" : "subUser2-1-2 file ico", "folderId" : "role1212" , "fileicon" : true}
]
}
]
}
]
}
]
I have created POJO for same and was able to add array elements in, but unable to add one more array inside or below the element. Please suggest.
below are the pojo I am using.
public class TargetFolder
{
private TargetChildren[] children;
private String roleName;
private String expanded;
private Long folderId;
public TargetFolder(String roleName,
String isFolder, Long folderId, TargetChildren[] folderList) {
super();
this.roleName = roleName;
this.expanded = isFolder;
this.folderId = folderId;
this.children = folderList;
}
public TargetChildren[] getChildren ()
{
return children;
}
public void setChildren (TargetChildren[] children)
{
this.children = children;
}
public String getRoleName ()
{
return roleName;
}
public void setRoleName (String roleName)
{
this.roleName = roleName;
}
public String getExpanded ()
{
return expanded;
}
public void setExpanded (String expanded)
{
this.expanded = expanded;
}
public Long getFolderId ()
{
return folderId;
}
public void setFolderId (Long folderId)
{
this.folderId = folderId;
}
#Override
public String toString()
{
return "ClassPojo [children = "+children+", roleName = "+roleName+", expanded = "+expanded+", folderId = "+folderId+"]";
}
}
and
public class TargetChildren
{
private String fileicon;
private String roleName;
private long folderId;
public TargetChildren(String roleName, String fileicon, long folderId) {
super();
this.fileicon = fileicon;
this.roleName = roleName;
this.folderId = folderId;
}
public String getFileicon ()
{
return fileicon;
}
public void setFileicon (String fileicon)
{
this.fileicon = fileicon;
}
public String getRoleName ()
{
return roleName;
}
public void setRoleName (String roleName)
{
this.roleName = roleName;
}
public long getFolderId ()
{
return folderId;
}
public void setFolderId (long folderId)
{
this.folderId = folderId;
}
#Override
public String toString()
{
return "ClassPojo [fileicon = "+fileicon+", roleName = "+roleName+", folderId = "+folderId+"]";
}
}
and below is the logic I am using to generate the JSON:
for(int i = 0; i<folderList.size();i++)
{
if(folderList!=null)
{
subList = (List)folderList.get(i);
childFolders[i] = new TargetChildren((String)subList.get(0),(String)subList.get(2),(Long)subList.get(1));
JSONArray arr = new JSONArray();
if(((String)subList.get(2)).equals("true"))
{
arr.put(i, childFolders[i]);
}
System.out.println(arr.toString());
//TargetChildren [] testArr = new TargetChildren[] { new TargetChildren("Folder", "folderName", 226886843L)};
}
}
TargetFolder targetFolder = new TargetFolder(parentFoldername,isFolder,folderId, childFolders);
JSONObject jsonObject = new JSONObject(targetFolder);
String jsonString = jsonObject.toString();
System.out.println("JSON TO UI------ "+jsonString);
The most elegant and simple solution I can think of is adding a toJSON method to your POJOs and let it handle the serializing itself.
For the TargetFolder:
public JSONObject toJSON(){
JSONObject out = new JSONObject();
out.put("rolename", rolename);
out.put("expanded", expanded);
out.put("folderID", folderId);
JSONArray children = new JSONArray();
for(int i = 0; i < this.children.length; i++){
children.push(this.children[i].toJSON());
}
out.put("children", children);
return out;
}
Do the same for the TargetChildren and then you can convert it to JSON by calling:
myTargetFolder.toJSON();
This way you don't need to worry about the recursive structure of the resulting JSON.
If you add a constructor which takes a JSONObject, you can ensure consistent serialization and deserialization in one place.
There is also the GSON library from Google, which should achieve essentially the same, but I never used it, so I cannot say how it would work with that.
P.S.: You might want to create a common superclass for TargetFolder and TargetChild and use that as the datatype for the children-array, because from the JSON it seems like this array can contain objects with TargetFolder-properties ("expanded" and "children") and objects with TargetChild-properties ("fileicon")