Shimul
Shimul

Reputation: 469

How to use GSON to encode String array data into JSON properly?

I am using GSON in my Java project to encode data ( that are fetched from database and stored into a String array ) in JSON format. Everything looks OK but the problem is with the size of String. For example I have the following String array:

String [] data = new String[12];

Suppose my String array contains the following data: {"ABC", "DEF", "GH", "IJ"}

Then the encoded JSON data are: ["ABC", "DEF", "GH", "IJ", "\u0000", null, null, null, null, null, null]

The number of null value in the JSON data is depends on the number of data available in my String array.

As the data is retrieved from database so I can't declare a specific size for my String array.

I am using the following code to encode String data into JSON format.

Gson gs = new Gson();
gs.toJson(data); //data String array contains data from database

Can anyone tell me how can I skip/remove those null value from my JSON data?

Upvotes: 1

Views: 1461

Answers (2)

sargue
sargue

Reputation: 5875

First of all an advice not directly related to the question. In a comment you say:

As I load data in the format data[index++], to remove unwanted garbage, I use data[index] = "\0". maybe \u000 is added for this.

I strongly suggest you load data into a List as you don't seem very comfortable working with arrays.

Instead of String [] data = new String[12] use List<String> data = new ArrayList<>(). Then, when loading data, instead of data[index++] use data.add(s).

Then the call new Gson().toJson(data) will work as you expect.

Anyway, to answer exactly your question you can just clean the array.

String [] data = {"ABC", "DEF", "GH", "IJ", "\u0000", null, null, null, null, null, null};
System.out.println("data = " + new Gson().toJson(data));
int i = 0;
for (; i < data.length && data[i] != null && !Objects.equals(data[i],"\u0000"); i++) ;
String[] cleanData = Arrays.copyOf(data, i);
System.out.println("cleanData = " + new Gson().toJson(cleanData));

The output of that code is this:

data = ["ABC","DEF","GH","IJ","\u0000",null,null,null,null,null,null]
data = ["ABC","DEF","GH","IJ"]

Upvotes: 0

Zircon
Zircon

Reputation: 4707

If you're uncomfortable working with array sizes, use an ArrayList and add each result from your database to it. Then when you're done with the database side of things:

data = arrayList.toArray(new String[arrayList.size()]);

This guarantees that the data object is just the right size to hold your data.

Upvotes: 1

Related Questions