我正在使用websocket和JsonNode开发Play framewrok 2。前端通过websocket连接到play框架后端。我将一个javascript数组转换为json节点,并通过使用webscocket连接将其发送到后端。现在我的问题是如何将json对象转换为java数组或任何合适的结构,以便操作数据。
这是我创建的的json对象
var myjeson = {"x":arrayX,"y":arrayY} ;
这是动态填充的阵列
function pixelCount ()
{ arrayX[counter] = xcoordinate;
arrayY[counter] = ycoordinate;
socket.send(" from array X,Y "+arrayX[counter]+ " " +arrayY[counter]);
++counter;
}
下面的代码发送数据
$('button.send').click(function() {
sock.send(JSON.stringify(myjeson));
在服务器端,我有以下代码
public static WebSocket<JsonNode> givenIn() {
return new WebSocket<JsonNode>() {
// called when the websocket is established
public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
// register a callback for processing instream events
in.onMessage(new Callback<JsonNode>() {
public void invoke(JsonNode event) {
Logger.info(event.toString());
}
当我检查日志时,消息被传递:下面是日志信息[info]应用程序-
{"x":
[78.72727298736572,79.72727298736572,82.72727298736572,
7298736572,93.72727298736572,83.72727298736572132.72727298736572],
"y":
[82.6363639831543,82.6363639831543,63.54545593261719,63.54545593261719,64.545455932
61719,65.54545593261719,70.54545593261719,189.5454559326172,188.5454559326172]}
现在我想把这些数据放在一个数组中,这样我就可以访问它们。任何建议都将受到赞赏。也欢迎其他建议。
将我的评论移到一个答案上,因为它得到了很多支持。
这应该是OP所需要的:
new ObjectMapper().convertValue(jsonNode, ArrayList.class)
使用树模型快速实现这一点的方法。。。将JSON字符串转换为JsonNode的树:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree("...<JSON string>...");
然后提取子节点并将其转换为列表:
List<Double> x = mapper.convertValue(rootNode.get("x"), ArrayList.class);
List<Double> y = mapper.convertValue(rootNode.get("y"), ArrayList.class);
一个稍长但有争议的更好方法是定义一个表示您期望的JSON结构的类:
public class Request {
List<Double> x;
List<Double> y;
}
然后直接反序列化如下:
Request request = mapper.readValue("...<JSON string>...", Request.class);
"…如何将json对象转换为java数组"
import com.google.common.collect.Streams;
public void invoke(JsonNode event) {
Streams.stream(event.withArray("x").elements())
.forEach( num -> Logger.info(num.asDouble()) )
}
诀窍是首先使用"elements()"方法获取Iterator对象,然后使用Guava"stream"方法获取流。一旦你有了流,你就可以进行各种数组操作(例如过滤、映射)来消耗你的数据。
答案主要在Jackson文档和教程中;
有几种方法可以将JsonNode转换为有用的数据。
如果你事先知道数据的结构,你可以使用数据绑定方法:对于"完全"绑定,使一个类对应于所有字段);对于结构化程度较低的方法,"原始"绑定允许您使用泛型对象。
否则,树模型方法应该适用于您;您将在链接页面中找到的示例与您的用例非常吻合。
请尝试这个例子,然后如果您有更具体的问题,请返回确切的实践或系统哲学问题!
Stefano在接受的答案中提到的树模型方法的快速答案:
JsonNode rootNode = new ObjectMapper().readTree(new StringReader(jsonStr));
JsonNode x=rootNode.get("x");
System.out.println(x.getNodeType());//should print: ARRAY
Iterator<JsonNode> arrayIterator=x.iterator();
List<Double> xList=new ArrayList<Double>();
while(arrayIterator.hasNext()) {
JsonNode elementInX=arrayIterator.next();
Double xDoubleValue=elementInX.asDouble();
xList.add(xDoubleValue);
}
Double[] xArray=new Double[xList.size()];
xList.toArray(xArray);//xArray now should be what you want
//do the same thing to y