我有一个android代码,它从数据库mysql获取数据并使用php来实现。代码运行良好但现在挑战是削减json数据。
这是我收到的json。
{"university":[{"University_Name":"New York University "},{"University_Name":"University Of Mississippi"},{"University_Name":"University Of London"},{"University_Name":"Birmingham University"}]}
我希望该应用程序能够像伯明翰大学那样展示。
下面是我的android代码:
public class MainActivity extends Activity {
//
TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.enableDefaults(); // This line is very usefull
resultView = (TextView)findViewById(R.id.result);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://10.0.0.54:80/connector/get_categories.php");
json.put("service", "GOOGLE");
Log.i("jason Object", json.toString());
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent(); // Get the
// data in
// the
// entity
String a = convertStreamToString(in);
Log.i("Read from Server", a);
Context context = getApplicationContext();
CharSequence text = "We are Connected";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, a, duration);
toast.show();
//This code displays
resultView.setText(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
答案 0 :(得分:1)
使用此代码解析数据
JSONObject jObj=new JSONObject(a);
JSONArray dataArray=jObj.optJSONArray("university");
List<String> dataList=new ArrayList<String>();
for(int i=0;i<dataArray.length();i++)
{
dataList.add(dataArray.optJSONObject(i).getString("University_Name"));
Toast toast = Toast.makeText(context,""+dataArray.optJSONObject(i).getString("University_Name"), duration);
toast.show();
}
只需用我的代码替换你的吐司
答案 1 :(得分:0)
使用gson将JSON转换为对象。
答案 2 :(得分:0)
您可以使用Google GSON库轻松完成此操作。 试试here,GOSN库将json数据转换为普通的java类,反之亦然。
答案 3 :(得分:0)
请尝试这种方式,希望这有助于您解决问题。
public class MainActivity extends Activity {
private TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.enableDefaults(); // This line is very usefull
resultView = (TextView)findViewById(R.id.result);
getUniversity(new WebServicesCallListener() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
resultView.setText(response);
try{
JSONObject jsonRespone = new JSONObject(response);
JSONArray universityJsonArray = jsonRespone.getJSONArray("university");
ArrayList<String> universityList = new ArrayList<String>();
for (int i=0;i<universityJsonArray.length();i++){
universityList.add(universityJsonArray.getJSONObject(i).getString("University_Name"));
}
for(String university : universityList){
System.out.print("University Name : "+ university);
}
}catch (Throwable e){
e.printStackTrace();
}
}
});
}
public void getUniversity(final WebServicesCallListener targer){
new AsyncTask<Void,Void,String>(){
@Override
protected String doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://10.0.0.54:80/connector/get_categories.php");
json.put("service", "GOOGLE");
Log.i("jason Object", json.toString());
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent(); // Get the
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
targer.onResponse(s);
}
}.execute();
}
public interface WebServicesCallListener {
public void onResponse(String response);
}
}
答案 4 :(得分:0)
下面的代码有点hackish,正如其他人写的那样,你应该使用像GSON这样的东西。无论如何,如果你想要每个项目的祝酒通知:
try {
JSONArray array = new JSONObject(a).getJSONArray("university");
for (int i = 0; i < array.length(); i++) {
String name = array.getJSONObject(i).getString("University_Name");
Toast.makeText(context, name, duration).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
如果你想要一个toast显示用逗号分隔的所有项目,例如:
String name = "";
String separator = ", ";
try {
JSONArray array = new JSONObject(a).getJSONArray("university");
for (int i = 0; i < array.length(); i++) {
if (i == array.length() - 1) {
separator = "";
}
name = name
+ array.getJSONObject(i).getString("University_Name")
+ separator;
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(context, name, duration).show();
一个非常简单的例子让你入门:
首先创建一个这样的xml布局(让我们称之为 list_item.xml :
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
创建适配器类(我们称之为 UniversitiesAdapter.java ):
public class UniversitiesAdapter extends BaseAdapter {
private JSONArray array;
private LayoutInflater inflater;
public UniversitiesAdapter(Context context, JSONArray array) {
this.array = array;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ViewHolder {
private TextView textView;
}
public int getCount() {
return array.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.list_item, null, true);
holder = new ViewHolder();
holder.textView = (TextView) view.findViewById(R.id.text_view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.textView.setText(array.getJSONObject(position).getString("University_Name"));
return view;
}
}
在您的活动中:
private UniversitiesAdapter adapter;
private ListView listView;
listView = (ListView) findViewById(R.id.your_list_view_id);
一旦得到你的回复('a'的值):
adapter = new UniversitiesAdapter (context, new JSONObject(a).getJSONArray("university"));
listView.setAdapter(adapter);