我有这段代码,我试图从这个字符串中获取项目
但它失败了
我使用过eclipse IDE
我从远程主机解析json字符串
package selectDB;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class selectDB
{
public static void main(String[] args) throws IOException, ParseException
{
String line;
String s = "";
URL u = new URL("http://192.168.3.1/android/select.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(; (line = reader.readLine()) != null;)
{
s+=line;
}
System.out.println(s);
try{
JSONObject jObject = new JSONObject(s);
String projecname=(String) jObject.get("name");
System.out.print(projecname);
}catch(Exception e)
{}
}
}
结果Json字符串就像这样
{"result" : "true" , "messages" : [{"id":"866343023633578","latitute":"27","longitude":"31","number_phone":"01113171374"},{"id":"352168066354050","latitute":"27","longitude":"31","number_phone":"202222"},{"id":"50","latitute":"50","longitude":"100","number_phone":"50"},{"id":"110","latitute":"50","longitude":"50","number_phone":"110"},{"id":"120","latitute":"27","longitude":"31","number_phone":"120"},{"id":"130","latitute":"28","longitude":"29","number_phone":"120"},{"id":"140","latitute":"30","longitude":"40","number_phone":"140"},{"id":"800","latitute":"60","longitude":"30","number_phone":"800"},{"id":"353629054230064","latitute":"70","longitude":"80","number_phone":"120"}]}
请帮帮我
谢谢
答案 0 :(得分:0)
您必须使用json string
JSONObject
解析为JSONParser
您不能简单地使用字符串对JSONObject
进行参数设置。
所以你必须这样做:
JSONParser parser = new JSONParser();
JSONObject jObject=(JSONObject)parser.parse(jsonstr);
String projecname=(String) jObject.get("name");