Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make JSON.stringify work on a NativeJavaArray? [duplicate]

Is it possible to make a 2D array in java serializable?

If not, i am looking to "translate" a 3x3 2D array into a Vector of Vectors.

I have been playing around with vectors, and I am still unsure of how to represent that. Can anyone help me?

Thanks!

like image 633
littleK Avatar asked Sep 23 '09 16:09

littleK


People also ask

Why JSON Stringify does not work on array?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.

Does JSON Stringify escape double quotes?

stringify does not act like an "identity" function when called on data that has already been converted to JSON. By design, it will escape quote marks, backslashes, etc. You need to call JSON. parse() exactly as many times as you called JSON.

Does JSON Stringify work on nested objects?

If your deeply-nested object or array only includes certain primitive values (strings, numbers, boolean, and null), then you can use JSON. parse() & JSON. stringify() to deep copy without issues.

Can you use JSON Stringify on an array?

While we're converting an object literal into a JSON string in this example, JSON. stringify() also works with arrays.


1 Answers

Arrays in Java are serializable - thus Arrays of Arrays are serializable too.

The objects they contain may not be, though, so check that the array's content is serializable - if not, make it so.

Here's an example, using arrays of ints.

public static void main(String[] args) {

    int[][] twoD = new int[][] { new int[] { 1, 2 },
            new int[] { 3, 4 } };

    int[][] newTwoD = null; // will deserialize to this

    System.out.println("Before serialization");
    for (int[] arr : twoD) {
        for (int val : arr) {
            System.out.println(val);
        }
    }

    try {
        FileOutputStream fos = new FileOutputStream("test.dat");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(twoD);

        FileInputStream fis = new FileInputStream("test.dat");
        ObjectInputStream iis = new ObjectInputStream(fis);
        newTwoD = (int[][]) iis.readObject();

    } catch (Exception e) {

    }

    System.out.println("After serialization");
    for (int[] arr : newTwoD) {
        for (int val : arr) {
            System.out.println(val);
        }
    }
}

Output:

Before serialization
1
2
3
4
After serialization
1
2
3
4
like image 78
brabster Avatar answered Oct 16 '22 05:10

brabster