我想使用套接字读取Json URL并将其显示在文本框中。
当我使用指定网址以外的网址时,会显示输出文件。但它与我的URL不一样。 URL中的内容非常大(大约184,523个字符)。
以下是我正在使用的代码:
public class MainActivity extends Activity {
URLConnection feedUrl = null;
String json="";
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void, Void, Void>(){
@Override
protected void onPreExecute() {
txt=(TextView)findViewById(R.id.myresponse);
txt.setText("intialize");
}
@Override
protected Void doInBackground(Void... params) {
URLConnection feedUrl;
try {
feedUrl = new URL("http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week").openConnection();
InputStream is = feedUrl.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
json= sb.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
txt.setText(json);
}
}.execute();
}
}
网址为http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week。请有人知道它为什么没有运行?
还有一个问题:如果我只想打印JSON文件的指定对象,该怎么办? 例如,如果我想打印整个第5个对象而不是整个文件。在这种情况下我该怎么做?
答案 0 :(得分:0)
首先,您必须格式化结果,以便获得实际的JSON:
Matcher matcher = Pattern.compile(Pattern.quote("callback(") + "(.*?)" + Pattern.quote(");")).matcher(json);
while (matcher.find())
json = matcher.group(1);
获得格式化的json后,需要将其转换为JSONObject
try{
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("features"); //get the features array
JSONObject myObject= array.getJSONObject(5); //get the element 5
}catch(Exception e){
e.printStackTrace();
}
现在你有一个名为myObject的jsonobject,带有第5个功能。