elemental.json 和 com.google.json 库有什么区别?

What is the difference between elemental.json and com.google.json library?

为什么我们 elemental.json 库超过 com.google.json?

我正在努力在 Vaadin 7 中创建 JsonArray。

在Json.createArray() 中没有添加方法。如何创建 json 数组?

我想创建一个像这样的数组:

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}, 
];

我是不是漏掉了什么?

根据 this official statement,从 7.4.0 elemental.json.* 开始替换旧包。

我试了一下,因为我也必须适应这些变化,我发现至少有这两种可能性:

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));
    }
}

哪个输出

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
  }
]

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