如何在android中创建JSON格式数据?

时间:2012-05-23 10:13:51

标签: android json

我需要将一些参数传递给我需要传递的服务器,如下所示 格式

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

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

我使用As shown in example 5.3尝试了此操作,但在obj.writeJSONString(out);此行显示错误。任何人都可以帮忙解决这个问题。

提前致谢

4 个答案:

答案 0 :(得分:38)

尽管如此,你想要的输出是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"
             ]
           }
         }

答案 1 :(得分:6)

您可以使用JSONObject并使用它构建数据。

以下是Documentation link

jsonObject.toString() // Produces json formatted object

答案 2 :(得分:2)

首先,您必须在代码

之后创建单独的类HttpUtil.java.See
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;
}

}

答案 3 :(得分: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();
}