13

我需要将一些参数传递给服务器,我需要按以下格式传递

{
  "k2": {
    "mk1": "mv1",
    "mk2": [
      "lv1",
      "lv2"
    ]
  }
}

那么如何在android中生成这种格式。

我使用如示例 5.3 中所示的方法尝试了此操作,但在obj.writeJSONString(out);此行显示错误。任何人都可以帮助解决这个问题。

提前致谢

4

4 回答 4

39

根本不是这样,您想要的输出是 JSONObject 中的 JSONArray 和另一个 JSONObject 中的 JSONObject。因此,您可以单独创建它们,然后可以将它们组合在一起。如下。

try {
            JSONObject parent = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            jsonArray.put("lv1");
            jsonArray.put("lv2");

            jsonObject.put("mk1", "mv1");
            jsonObject.put("mk2", jsonArray);
            parent.put("k2", jsonObject);
            Log.d("output", parent.toString(2));
        } catch (JSONException e) {
            e.printStackTrace();
        }

输出-

       {
           "k2": {
             "mk1": "mv1",
             "mk2": [
               "lv1",
               "lv2"
             ]
           }
         }
于 2012-05-23T10:28:55.407 回答
6

您可以使用JSONObject它来使用和构建您的数据。

这是文档链接

jsonObject.toString() // Produces json formatted object
于 2012-05-23T10:16:28.600 回答
2

您好,首先您必须创建单独的类 HttpUtil.java。请参阅以下代码

public class HttpUtil {

// lat=50.2911 lon=8.9842

private final static String TAG = "DealApplication:HttpUtil";

public static String get(String url) throws ClientProtocolException,
        IOException {
    Log.d(TAG, "HTTP POST " + url);
    HttpGet post = new HttpGet(url); 
    HttpResponse response = executeMethod(post);
    return getResponseAsString(response);
}

public static String post(String url, HashMap<String, String> httpParameters)
        throws ClientProtocolException, IOException {
    Log.d(TAG, "HTTP POST " + url);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
            httpParameters.size());
    Set<String> httpParameterKeys = httpParameters.keySet();
    for (String httpParameterKey : httpParameterKeys) {
        nameValuePairs.add(new BasicNameValuePair(httpParameterKey,
                httpParameters.get(httpParameterKey)));
    }

    HttpPost method = new HttpPost(url);
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
    System.out.println("**************Request=>"+urlEncodedFormEntity.toString());
    method.setEntity(urlEncodedFormEntity);
    HttpResponse response = executeMethod(method);

    return getResponseAsString(response);
}

private static HttpResponse executeMethod(HttpRequestBase method)
        throws ClientProtocolException, IOException {
    HttpResponse response = null;
    HttpClient client = new DefaultHttpClient();
    response = client.execute(method);
    Log.d(TAG, "executeMethod=" + response.getStatusLine());
    return response;
}

private static String getResponseAsString(HttpResponse response)
        throws IllegalStateException, IOException {
    String content = null;
    InputStream stream = null;
    try {
        if (response != null) {
            stream = response.getEntity().getContent();
            InputStreamReader reader = new InputStreamReader(stream);
            BufferedReader buffer = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String cur;
            while ((cur = buffer.readLine()) != null) {
                sb.append(cur + "\n");
            }
            content = sb.toString();
            System.out.println("**************Response =>"+content);
        }
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
    return content;
}

}
于 2013-04-17T11:59:11.973 回答
0

这个例子是帮助你调用这个函数,它将返回 JSON 作为字符串值。试试看

 public String getResult() {
    JSONObject userResults = null;
    try {
        userResults = new JSONObject();
        userResults.put("valueOne",str_one);
        userResults.put("valueTwo", str_two);
        userResults.put("valueThree" ,str_three);
        userResults.put("valueFour", str_four);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return userResults.toString();
}
于 2016-10-27T13:47:01.293 回答