Enrichman
Enrichman

Reputation: 11337

Java to JavaScript array of arrays?

I've to create from Java a JSON structure like this one:

[ [ timestamp , number ],[ timestamp , number ] ]

for using it on Highcharts graphs.

I've used a "LinkedList of LinkedList" structure that I've found formatting in json in the same way, and it works.

I wished to know if there's another way to do it. A LinkedList of LinkedList sounds weird..

EDIT:

Maybe the question wasn't clear. I'm not asking how to convert the array-of-arrays in json but WHAT to convert.

In my case I know the result of the conversion and I can choose the starting structure. Other structures, instead of "LinkedList of LinkedLists" that json-ized are like this:

[ [ x, y ] , [ z, k ] , ... ]

Upvotes: 0

Views: 311

Answers (4)

Ashok Patel
Ashok Patel

Reputation: 54

If u dont want to use any collection class then by simply using following code u can make the string required to u for JSON.In following code u can keep the num variable value dynamic.

StringBuilder sb = new StringBuilder();
        sb.append("[");
        int num = 5;
        for(int i=0;i<num;i++)
        {
            sb.append("[");
            sb.append(new Date().getTime() + "," + (i+1));
            sb.append("]");
            if((i+1)<num)
                sb.append(",");
        }
        sb.append("]");

Upvotes: 1

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You can use List of arrays:

List<long[]> hcData = new ArrayList<long[]>();
//add the pairs
hcData.add(new long[]{date.getTime(), number});

Just make sure your list (hcData) will be sorted according to the date, so that you don't have to play with it on the client side.

Upvotes: 0

Sergey Savenko
Sergey Savenko

Reputation: 666

Good day!

LinkedList-of-LinkedLists is a bad way to do it, as it does not allow you to extend your structure further. You'd better take a glance at how it is implemented in existent Java-JSON wrappers. You surely need to make some class which would have encapsulated a linked list inside it. This way you could make even more complex structures without loosing readability.

Upvotes: 0

Paul
Paul

Reputation: 20091

Another way? You haven't really said how you've already done it. I've found Json-lib easy to use and reliable, and it should turn a Java array-of-arrays into JSON for you.

Upvotes: 0

Related Questions