[英]Obtain complex JSON structure using java
I have pasted a sample JSON Structure which I am trying to achieve using java program finally the output should be in JSONObject.我已经粘贴了一个示例 JSON 结构,我试图使用 java 程序实现它,最终输出应该在 JSONObject 中。 I tried using map but it became very complex if I was not going wrong.我尝试使用地图,但如果我没有出错,它会变得非常复杂。
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster"},
{"name": "CommunityStructure"},
{"name": "HierarchicalCluster"},
{"name": "MergeEdge"}
]
}]
},
{
"name": "graph",
"children": [
{"name": "BetweennessCentrality"},
{"name": "LinkDistance"},
{"name": "MaxFlowMinCut"},
{"name": "ShortestPaths"},
{"name": "SpanningTree"}
]
}
]
}
You can try using GSON library by google.您可以尝试使用谷歌的 GSON 库。 You can create Java objects and GSON turns them into JSON automatically.您可以创建 Java 对象,GSON 会自动将它们转换为 JSON。 Have a look: https://code.google.com/p/google-gson/ The disadvantage of using JSONObject directly would be that it would become very complicated in your case.看看: https : //code.google.com/p/google-gson/直接使用 JSONObject 的缺点是它会变得非常复杂。 And as the data you want to put in JSON grows, it would become very difficult.随着您想要放入 JSON 的数据增长,这将变得非常困难。
Use JSONObject使用JSONObject
For example:例如:
myString = new JSONObject().put("JSON", "Hello, World!").toString(); myString = new JSONObject().put("JSON", "Hello, World!").toString();
produces the string {"JSON": "Hello, World"}.产生字符串 {"JSON": "Hello, World"}。
Using GSON library is easy.使用GSON库很容易。 Create Person class with an attribute to an array of same class.创建具有相同类数组属性的 Person 类。
class Person {
private String name;
private Person[] children;
//getters
//setters
}
and then, use it to get instance from json然后,使用它从 json 获取实例
// Create person
Person person = new Gson().fromJson(jsonString, Person.class);
// Get children
Person[] childrens = person.getChildren();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.