为什么我们在com.google.json上有elemental.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},
];
我错过了什么吗?
答案 0 :(得分:1)
根据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
}
]