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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10717838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:44:53  来源:igfitidea点击:

How to create JSON format data in android?

androidjson

提问by Harish

I need to pass some parameters to server that i need to pass as below format

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

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

So how can generate this format in android.

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

I tried this using the As shown in example 5.3but it is showing a error at obj.writeJSONString(out);this line. Can anyone please help in solving this.

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

Thanks In Advance

提前致谢

回答by Lalit Poptani

Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.

虽然根本不是这样,但您想要的输出是 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();
        }

Output-

输出-

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

回答by ChristopheCVB

You can use JSONObjectand construct your data with it.

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

Here is the Documentation link

这是文档链接

jsonObject.toString() // Produces json formatted object

回答by Gomathi

Hi first you have to create separate class HttpUtil.java.See following the code

您好,首先您必须创建单独的类 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;
}

}

回答by Mathan Chinna

This example is help you just call this function it will return JSON as string value.. Try it

这个例子可以帮助你调用这个函数,它会返回 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();
}