What is the difference between elemental.json and

2019-09-07 06:09发布

问题:

Why do we have elemental.json library over com.google.json?

I'm struggling with the creation of JsonArray in Vaadin 7.

In Json.createArray() there is no add method. How can I create a json array?

I want to create an array like:

var shapeArray = 
[
    {type: 'rectangle', x:50, y:50, width : 50, height: 50},
    {type: 'circle', x:75, y:150,  r : 20}, 
    {type: 'rectangle', x:50, y:200, width : 100, height: 20},
    {type: 'circle', x:75, y:300,  r : 30}, 
];

Am I missing something?

回答1:

As per this official statement, starting with 7.4.0 elemental.json.* replaces the old packages.

I've played around a bit as I also had to adapt to these changes and I found at least these 2 possibilities:

import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonValue;
import elemental.json.impl.JsonUtil;
import org.junit.Test;

public class JsonTest {

    @Test
    public void shouldParseJson() {
        JsonArray array = JsonUtil.parse("[\n" +
                "    {'type': 'rectangle', 'x':50, 'y':50, 'width': 50, 'height': 50},\n" +
                "    {'type': 'circle', 'x':75, 'y':150,  'r' : 20}, \n" +
                "    {'type': 'rectangle', 'x':50, 'y':200, 'width' : 100, 'height': 20},\n" +
                "    {'type': 'circle', 'x':75, 'y':300,  'r' : 30}, \n" +
                "]");


        System.out.println("Parsed string array:\n" + JsonUtil.stringify(array, 2));
    }


    @Test
    public void shouldCreateArray() {
        //for the sake of brevity I'll create the object by also parsing a string, but you get the general idea
        JsonValue object = JsonUtil.parse("{'type': 'rectangle', 'x':50, 'y':50, 'width': 50, 'height': 50}");
        JsonArray array = Json.createArray();
        array.set(0, object);

        System.out.println("Manually created array:\n" + JsonUtil.stringify(array, 2));
    }
}

Which output

Parsed string array:
[
  {
    "type": "rectangle",
    "x": 50,
    "y": 50,
    "width": 50,
    "height": 50
  },
  {
    "type": "circle",
    "x": 75,
    "y": 150,
    "r": 20
  },
  {
    "type": "rectangle",
    "x": 50,
    "y": 200,
    "width": 100,
    "height": 20
  },
  {
    "type": "circle",
    "x": 75,
    "y": 300,
    "r": 30
  }
]

and

Manually created array:
[
  {
    "type": "rectangle",
    "x": 50,
    "y": 50,
    "width": 50,
    "height": 50
  }
]