如何在安卓系统中创建JSON格式的数据?

13

我需要将一些参数传递到服务器,我需要按以下格式进行传递:

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

那么在安卓中如何生成这种格式呢。

我尝试使用示例5.3中所示的方法,但在obj.writeJSONString(out);这一行出现了错误。请有人帮忙解决一下。

先行谢过。

4个回答

39

不过,你想要的输出格式是一个JSONObject内部包含一个JSONArray 和 另一个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"
             ]
           }
         }

+1 我对 JSON 解析还很陌生。这个清晰的例子就是我所需要的 :-) - rockstar
@LalitPoptani 在 Log.d("output", parent.toString(2)); 中的 2 是什么?是空格吗? - Compaq LE2202x
@CompaqLE2202x 是的,这是Json输出中的间距和格式。 - Lalit Poptani

6
你可以使用 JSONObject 构建数据。
这是 文档链接
jsonObject.toString() // Produces json formatted object

你能发布异常详细信息吗? - ChristopheCVB
你正在导入 org.json.JSONObject 吗? - ChristopheCVB

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;
}

}

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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接