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

标签 java json vaadin vaadin7

为什么我们有 elemental.json 库而不是 com.google.json?

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

在 Json.createArray() 中没有 add 方法。如何创建 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
  }
]

关于java - elemental.json 和 com.google.json 库有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207410/

相关文章:

java - getHardwareAddress 不适用于 IBMi (iSeries) reqd for OrientDB

java - twitter4j 3.0.5 : sun. security.validator.ValidatorException:PKIX 路径构建失败

java - itext 马拉地语(印度)语言显示问题

javascript - php输出到带有json的javascript数组

json - WSO2 API Manager Auth 错误内容类型

Vaadin 14 主题 - 使用 "include"

JavaFx:TableView - 取消绑定(bind)所有属性

json - 如何在 Odoo Controller 中获取 JSON 数据?

java - 表单布局 : 1 caption for 2 fields

java - 带有VAADIN 8,Gradle和Spring Boot的 Canvas 插件