我面临以下困难:
我创建了一个JSONObject。
使用System.out.println (finalJson)
我得到下面的输出。根据{{3}},它是有效的JSON。但是当我尝试通过调用finalJson.toString ()
来获取String表示时,它只返回null。怎么可能?我在这里缺少什么?
{
"id": "cell: chris-VirtualBoxCell01",
"name": "cell: chris-VirtualBoxCell01",
"data": {},
"children": [
{
"id": "node: chris-VirtualBoxNode01",
"name": "node: chris-VirtualBoxNode01",
"data": {},
"children": [
{
"id": "applicationServer: C4Cluster_server1",
"name": "applicationServer: C4Cluster_server1",
"data": {},
"children": []
},
{
"id": "nodeAgent: nodeAgent",
"name": "nodeAgent: nodeAgent",
"data": {},
"children": []
}
]
},
{
"id": "deploymentManagerNode: chris-VirtualBoxCellManager01",
"name": "deploymentManagerNode: chris-VirtualBoxCellManager01",
"data": {},
"children": [
{
"id": "deploymentManager: deploymentManager",
"name": "deploymentManager: deploymentManager",
"data": {},
"children": []
}
]
}
]
}
以下是应该感兴趣的片段:
//Get JSON from Grails domain model
JSON json = ServerNode.findAll ("from ServerNode as s where s.root=true") as JSON;
//check result
System.out.println (json);
//turn into a JSONObject by chopping off surrounding []
String jsonString = json.toString ().substring (1, json.toString ().length ()-1);
//check result
System.out.println (jsonString);
//render to JSONObject
JSONObject jObject = new JSONObject (jsonString);
//modify structure a little more
JSONObject finalJson = modifyJson (jObject);
//check the final form (produces the above output)
System.out.println (finalJson);
//turn into string and print --> returns null
String jString = finalJson.toString ();
System.out.println (jString);