我使用以下代码在json对象中放置一个json数组;
import org.json.JSONObject;
public class PollingPoJo {
int id;
String topic;
String description;
String pollItem1;
String pollItem2;
String pollItem3;
String pollItem4;
ArrayList<String> pollingItem ;
public PollingPoJo(int id, String topic, String description, String pollItem1, String pollItem2, String pollItem3,
String pollItem4) {
super();
this.id = id;
this.topic = topic;
this.description = description;
this.pollItem1 = pollItem1;
this.pollItem2 = pollItem2;
this.pollItem3 = pollItem3;
this.pollItem4 = pollItem4;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPollItem1() {
return pollItem1;
}
public void setPollItem1(String pollItem1) {
this.pollItem1 = pollItem1;
}
public String getPollItem2() {
return pollItem2;
}
public void setPollItem2(String pollItem2) {
this.pollItem2 = pollItem2;
}
public String getPollItem3() {
return pollItem3;
}
public void setPollItem3(String pollItem3) {
this.pollItem3 = pollItem3;
}
public String getPollItem4() {
return pollItem4;
}
public void setPollItem4(String pollItem4) {
this.pollItem4 = pollItem4;
}
@Override
public String toString() {
pollingItem = new ArrayList<>();
pollingItem.add(pollItem1);
pollingItem.add(pollItem2);
pollingItem.add(pollItem3);
pollingItem.add(pollItem4);
String jObj = new JSONObject().put("id",id)
.put("topic", topic)
.put("description", description)
.put("pollingItems", pollItem1).toString();
return jObj;
}
}
稍后我使用以下代码生成响应。
@POST
@Path("polling")
@Produces(MediaType.APPLICATION_JSON)
public static String getCurrentPoll() {
ArrayList<PollingPoJo> output = new ArrayList<PollingPoJo>();
try {
Connection connection = MyResource.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM POLLING order by id desc limit 1 ");
output = new ArrayList<PollingPoJo>();
while (rs.next()) {
PollingPoJo trending = new PollingPoJo(rs.getInt("ID"), rs.getString("TOPIC"), rs.getString("DESCRIPTION"),
rs.getString("ITEM1"), rs.getString("ITEM2"), rs.getString("ITEM3"),
rs.getString("ITEM4"));
output.add(trending);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
但是生成的json响应中不包含json。虽然我在toString中嵌入了一个数组列表,但它没有显示出来。我怎样才能解决这个问题?
以下是预期的样本回复,
{&#34; topic&#34;:&#34; Fruits&#34;,&#34; description&#34;: &#34;我最喜欢的水果&#34;,&#34; id&#34;:1,
&#34; polling_items&#34;:[ &#34;项目1&#34;, &#34;项目2&#34;, &#34;项目3&#34; ]}
但它正在抛出以下回复,
[{ &#34;主题&#34;:&#34;水果&#34;, &#34;描述&#34;:&#34;我最喜欢的水果&#34;, &#34; id&#34;:1, &#34; pollingItems&#34;:&#34; item1&#34; }]
如您所见,pollingitems不包含json数组。我怎样才能解决这个问题?
答案 0 :(得分:1)
在你的PollingPoJo中,你应该有一个名为polling_items的集合。在PollingPoJo的构造函数中,将3,4,5,6个参数添加到此集合中。