Kaninchen Kaninchen - 2 years ago 125
Java Question

How to output json array in java?

Ok, for example, I got an array of data that look like this:

String[] data = {"cheese", "10.00", "bread", "3.99", "tomato", "4.99", ...};

Now I want to make it become the Json array of data, so it will be easier to process for the Client. So I want it look like this:


For that, I choose to use List and Hashmap to get what I want:

public String getOutput() {
List<Hashmap> list = null;
HashMap<String, String> map = new Hashmap<>();
string rawData = "";
BufferedInputStream in;

try {
// read text data from input stream
in = new BufferedInputStream(socket.getInputStream());
byte[] byteArr = new byte[1024];
int length;

// turn into string
while ((length = in.read(byteArr)) > 0)
rawData += new String(byteArr, 0, length);

String[] data = rawData.split(",");
int total = data.length;
int i = 0;

while(i < total) {
map.put("name", data[i]);
map.put("price", data[i+1]);
i += 2;
catch (Exception e) {
// exception process

return new Gson().toJson(list);

When I compile and execute it, it print only "null" on the Screen. Why? what do I miss?


@Sotirios I see why you get the NullPointerException but mine because the Original code is look like this, and my exception where catch-ed so I get just "null" on my screen.

And @sauumum, you got it right! I used the Eclipse Quick fix to fix the error of List when it ask for initialize at first time! It is really hard to see the
List<Hashmap> list = null;
is the source of problem because Eclipse's Quick fix is right at most of the time. And I thought it should be the
List<Hashmap> list = new List<>();
because class name need to be same usually, but yours won't get any error and works nicely than mine! that was weird.

Answer Source

It is only because you have List<Hashmap> list = null; . Initialize this with new ArrayList<>();

One more thing, are you sure that you are getting null on console and not NullPointerException as your code looks like?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download