一旦检查此图片,..并告诉我如何解决这个问题
我应用了上面的Json数组和Json Object in this link
但是当我运行它时,....这个响应我得到了consloe,...告诉我如何在Url中提供这些数据,...在tomcat的本地主机......
并且还会看到此链接以获取更多详细信息,.. How to Create a Restful service for a Huge JSON data using Java eclipse Tomcat7.0
答案 0 :(得分:1)
您的导入声明是什么样的?我使用org.json。*
首先你需要把json字符串放到一个字符串中,用BufferedReader逐行读取它。
然后你应该
JSONObject jsonObject = new JSONObject(json);
其中json是您使用BufferedReader
读取时获得的字符串以下是一个例子:
try {
InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8")));
try {
String json = rd.readLine();
} finally {
rd.close();
}
} catch (Exception e) {
System.out.println(e.toString());
}
JSONObject obj = new JSONObject(json);
答案 1 :(得分:1)
以下是如何在java中创建json字符串的更多示例:
public String createJSONArrayOfObjects() throws JSONException {
JSONArray list = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", true);
obj.put("nickname", "");
list.put(obj);
obj = new JSONObject();
obj.put("name" , "foo too");
obj.put("num", new Integer(200));
obj.put("balance", new Double(2000.21));
obj.put("is_vip", true);
obj.put("nickname", "");
list.put(obj);
return list.toString();
}
public String mixingJSONArrayAndObjects() throws JSONException {
JSONArray list1 = new JSONArray();
list1.put("foo");
list1.put(new Integer(100));
list1.put(new Double(1000.21));
JSONArray list2 = new JSONArray();
list2.put(true);
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", true);
obj.put("nickname", "");
obj.put("list1", list1);
obj.put("list2", list2);
return obj.toString();
}
public String createJSONArray() throws JSONException {
JSONArray list = new JSONArray();
list.put("foo");
list.put(100);
list.put(1000.21);
list.put(true);
return list.toString();
}
public void createJSONArrayFromString(String anArray) throws JSONException {
JSONArray list = new JSONArray(anArray);
for (int i = 0; i < list.length(); i++) {
switch (i) {
case 0:
System.out.println(i + " " + list.getString(i));
break;
case 1:
System.out.println(i + " " + list.getInt(i));
break;
case 2:
System.out.println(i + " " + list.getDouble(i));
break;
case 3:
System.out.println(i + " " + list.getBoolean(i));
break;
}
}
}
public String createObject() throws JSONException {
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", true);
obj.put("nickname", "");
return obj.toString();
}