在这里,解析JSON似乎是一个非常普遍的讨论话题。我已经查找过了,但仍然没有找到我需要的内容。
这是我的HttpClient代码:
public class CreateJsonRequest {
public static String SendJsonRequest(String URL, Map<String,Object> params){
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
JSONObject holder = new JSONObject();
for (Map.Entry<String, Object> m : params.entrySet()){
try {
holder.put(m.getKey(), m.getValue());
}
catch (JSONException e) {
Log.e("Hmmmm", "JSONException : "+e);
}
}
StringEntity se;
se = new StringEntity(holder.toString());
httpPost.setEntity(se);
httpPost.setHeader("Accept", "text/json");
httpPost.setHeader("Content-type", "text/json");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(entity != null){
final JSONObject respObject = new JSONObject(EntityUtils.toString(entity));
String result = respObject.toString();
parseJSON(result);
我正在使用 HttpClient 向服务器发送 JSON 请求,服务器会返回一个 JSON 响应。这个过程很顺利。现在我遇到了麻烦。我从服务器收到了一个 HttpEntity,然后将其转换为一个字符串,看起来像这样:
{"Make":"Ford","Year": 1975, "Model":"Mustang"}
。我想能够将这个字符串发送到我的 parseJSON(String jString)
方法中,并返回一个键值对映射。与其他帖子不同的是,我希望解析方法能够为我发送的任何 JSON 字符串创建一个键值对映射。因此,如果我发送了 {"Engine":"v8","Cylinders": 8, "Transmission":"Manual","Gears": 4}
,它仍然可以工作。这可行吗?如果可以,你能给我一些正确的方向吗?
Android
,对吧?或者我漏掉了什么?你在 android 应用程序中使用它似乎完全无关紧要。 - keyser