我是D3新手。当我正在努力的时候,我得到了一个要求,我必须建立一个像这样的json -
{
"nodes":[
{"name":"0","group":1},
{"name":"1","group":1},
{"name":"2","group":10},
{"name":"3","group":1},
{"name":"4","group":1}
],
"links":[
{"source":1,"target":0},
{"source":2,"target":0},
{"source":3,"target":0},
{"source":3,"target":2},
{"source":2,"target":4},
{"source":1,"target":4}
]
}
我所做的就是这样 -
"allCalls":[{"Name":"Voice","Data":"40"},
{"Name":"SMS","Data":"30"},
{"Name":"MMS","Data":"5"},
{"Name":"GPRS","Data":"20"},
{"Name":"Others","Data":"5"}],
"allCallsRatio":5}
这是servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start = request.getParameter("source");
String end = request.getParameter("count");
if (start == null && end == null) {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
ArrayList<IndCallType> ratios = new ArrayList<IndCallType>();
ratios.add(new IndCallType("Voice", "40"));
ratios.add(new IndCallType("SMS", "30"));
ratios.add(new IndCallType("MMS", "5"));
ratios.add(new IndCallType("GPRS", "20"));
ratios.add(new IndCallType("Others", "5"));
Gson gson = new Gson();
JsonArray arrayObj = new JsonArray();
for (int i = 0; i < ratios.size(); i++) {
IndCallType count = ratios.get(i);
JsonElement linObj = gson.toJsonTree(count);
arrayObj.add(linObj);
}
JsonObject myObj = new JsonObject();
myObj.addProperty("success", true);
myObj.add("allCalls", arrayObj);
myObj.addProperty("allCallsRatio", ratios.size());
System.out.println(myObj.toString());
我给了servlet的主要部分,我在这里建立了JSON。 但它不是我想要的......任何人都可以帮助我......
答案 0 :(得分:0)
我知道你需要一些东西来序列化你发布的第一个 JSON。最简单的方法是构建相应的POJO,然后使用Gson序列化它们。你可以忘记所有Json * .java的东西。 Gson将为您完成所有工作。
这是一个示例,您可以直接复制并运行到显示该想法的IDE中。您可以轻松地将其调整为您的代码。
package stackoverflow.questions;
import java.util.*;
import com.google.gson.Gson;
public class Q20162819 {
public static class Node {
String name;
Integer group;
public Node(String name, Integer group) {
this.name = name;
this.group = group;
}
}
public static class Link {
Integer source;
Integer target;
public Link(Integer source, Integer target) {
this.source = source;
this.target = target;
}
}
public static class Data {
List<Node> nodes = new ArrayList<>(); // java7
List<Link> links = new ArrayList<>(); // java7
}
/**
* @param args
*/
public static void main(String[] args) {
Data d = new Data();
d.links.add(new Link(0, 1));
d.links.add(new Link(2, 10));
d.links.add(new Link(1, 20));
d.nodes.add(new Node("1", 1));
d.nodes.add(new Node("1", 2));
d.nodes.add(new Node("3", 5));
Gson g = new Gson();
System.out.println(g.toJson(d));
}
}
这是结果(我使用external tool格式化了它。)
{
"nodes": [
{
"name": "1",
"group": 1
},
{
"name": "1",
"group": 2
},
{
"name": "3",
"group": 5
}
],
"links": [
{
"source": 0,
"target": 1
},
{
"source": 2,
"target": 10
},
{
"source": 1,
"target": 20
}
]
}