Android 如何从php服务器阵列解析json?
我从post向php服务器发送数据,它向我发送json数组: json数组响应(json文件并不总是相同的) 我的班级Android 如何从php服务器阵列解析json?,android,arrays,json,Android,Arrays,Json,我从post向php服务器发送数据,它向我发送json数组: json数组响应(json文件并不总是相同的) 我的班级 public class MainActivity extends Activity implements OnClickListener { private EditText value, etid, etmd5; private Button btn; private ProgressBar pb; private static final
public class MainActivity extends Activity implements OnClickListener
{
private EditText value, etid, etmd5;
private Button btn;
private ProgressBar pb;
private static final String LOGTAG = "LogsAndroid";
@Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value = (EditText) findViewById(R.id.editText1);
etid = (EditText) findViewById(R.id.etid);
etmd5 = (EditText) findViewById(R.id.etmd5);
btn = (Button) findViewById(R.id.button1);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
btn.setOnClickListener(this);
}
public void onClick (View v)
{
// TODO Auto-generated method stub
if (value.getText().toString().length() < 1)
{
// out of range
Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
}
else
{
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(value.getText().toString());
}
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>
{
@Override
protected Double doInBackground (String... params)
{
String datos=value.getText().toString();
// Create a new HttpClient and Post Header
HttpClient httpClient = getNewHttpClient();
HttpPost httppost = new HttpPost("https://xxxxxxxxxxxxx.xxxx/xxxxxxx");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Datos", datos));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.i(LOGTAG, responseBody);
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
} catch (IOException e)
{
// TODO Auto-generated catch block
}
return null;
}
protected void onPostExecute (Double result)
{
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate (Integer... progress)
{
pb.setProgress(progress[0]);
}
//to use https server
public HttpClient getNewHttpClient ()
{
try
{
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e)
{
return new DefaultHttpClient();
}
}
}
}
public类MainActivity扩展活动实现OnClickListener
{
私有编辑文本值,etid,etmd5;
专用按钮btn;
私人ProgressBar pb;
私有静态最终字符串LOGTAG=“LogsAndroid”;
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
值=(EditText)findViewById(R.id.editText1);
etid=(EditText)findViewById(R.id.etid);
etmd5=(EditText)findViewById(R.id.etmd5);
btn=(按钮)findViewById(R.id.button1);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
btn.setOnClickListener(此);
}
公共void onClick(视图v)
{
//TODO自动生成的方法存根
if(value.getText().toString().length()<1)
{
//超出范围
Toast.makeText(这是“请输入内容”,Toast.LENGTH_LONG.show();
}
其他的
{
pb.setVisibility(View.VISIBLE);
新建MyAsyncTask().execute(value.getText().toString());
}
}
私有类MyAsyncTask扩展了AsyncTask
{
@凌驾
受保护的双doInBackground(字符串…参数)
{
字符串datos=value.getText().toString();
//创建一个新的HttpClient和Post头
HttpClient HttpClient=getNewHttpClient();
HttpPost HttpPost=新的HttpPost(“https://xxxxxxxxxxxxx.xxxx/xxxxxxx");
尝试
{
//添加您的数据
List nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“Datos”,Datos));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//执行HTTP Post请求
HttpResponse response=httpClient.execute(httppost);
String ResponseBy=EntityUtils.toString(response.getEntity());
Log.i(日志标签、响应库);
}捕获(客户端协议例外e)
{
//TODO自动生成的捕捉块
}捕获(IOE异常)
{
//TODO自动生成的捕捉块
}
返回null;
}
受保护的void onPostExecute(双重结果)
{
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),“已发送命令”,Toast.LENGTH_LONG.show();
}
受保护的void onProgressUpdate(整数…进度)
{
pb.setProgress(progress[0]);
}
//使用https服务器
公共HttpClient getNewHttpClient()
{
尝试
{
KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
load(null,null);
SSLSocketFactory sf=新的MySSLocketFactory(信任商店);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params=新的BasicHttpParams();
HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
SchemeRegistry registry=新SchemeRegistry();
register(新方案(“http”,PlainSocketFactory.getSocketFactory(),80));
注册(新方案(“https”,sf,443));
ClientConnectionManager ccm=新的ThreadSafeClientConnManager(参数,注册表);
返回新的DefaultHttpClient(ccm,参数);
}捕获(例外e)
{
返回新的DefaultHttpClient();
}
}
}
}
我想在他的Edittext上显示每个值我不知道该怎么做,但我无法在我的应用程序上显示数据 为此,您需要创建如下对象:
public class MyObject{
public int id;
public String md5;
public MyImagesObject md5_img;
}
及
然后:
MyObject myObject = new Gson().fromJson(jsonString, MyImagesObject.class);
使用JSONObject。例如:
String response = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(jsonString);
int id = json.optInt("id", 0);
JSONObject jsonInner = json.optJSONObject("md5_img", null);
下面是如何将
字符串
响应主体解析为JSONObject
:
try {
JSONObject object = new JSONObject(responseBody);
long id = object.getLong("id");
String md5 = object.getString("md5");
JSONObject md5_img = object.getJSONObject("md5_img");
String image1 = object.getString("img1");
String image2 = object.getString("img2");
} catch (JSONException e) {
e.printStackTrace();
}
从那里,您可以决定是否要创建一个模型类来解析这些值,以便将其保存到数据库中,或者根据需要从内存中访问它。只有当您知道json响应中的数据时,才可以解析json。 以下操作有两种方法-
JSONObject jsonObject = new JSONObject(json);
int id = jsonObject.getInt("id");
String md5 = jsonObject.getString("md51");
JSONObject innerJSONObject=jsonObject.getJSONObject("md5_img");
或2。使用一些库,如GSON或JACKSON,直接解析类对象,正如Mathieu de Brito在上面所建议的那样。你是说“md5_img”:“md5_img”:“@SmitaNarayan它是json数组中的一个数组sorry my bad,这很好。json似乎是正确的:感谢这个web,在@dthacker之前,我不知道有什么关于解析json的建议?我喜欢,但json文件并不总是相同的,更一般的东西?例如,使用for each?如果你发布到一个URL,你应该总是期望在它的响应中使用相同的JSON结构。为什么每次都希望JSON结构不同?JSON并不总是相同的,因为我需要向服务器发送数据,然后根据每次发送的数据,我会收到不同的JSON。对于服务器响应来说,这似乎是一个糟糕的设计,很难检测到需要使用什么JSON解析方法。您可能需要考虑使用多个端点URL来发布不同的数据集,然后为每个URL提供委托解析方法。这样,您就可以始终依赖于JSON结构的稳定。您可以发布JSON响应可能返回的不同格式吗?
try {
JSONObject object = new JSONObject(responseBody);
long id = object.getLong("id");
String md5 = object.getString("md5");
JSONObject md5_img = object.getJSONObject("md5_img");
String image1 = object.getString("img1");
String image2 = object.getString("img2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonObject = new JSONObject(json);
int id = jsonObject.getInt("id");
String md5 = jsonObject.getString("md51");
JSONObject innerJSONObject=jsonObject.getJSONObject("md5_img");