【问题标题】:How to create JSON format data in android?如何在android中创建JSON格式数据?
【发布时间】:2012-05-23 10:13:51
【问题描述】:

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

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

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

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

提前致谢

【问题讨论】:

    标签: android json


    【解决方案1】:

    虽然根本不是这样,但您想要的输出是 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 我是 JSON 解析新手。这个清晰的例子就是我所需要的:-)
    • @LalitPoptani Log.d("output", parent.toString(2)); 中的 2 是什么?是间距吗?
    • @CompaqLE2202x 是的,就是 Json 输出中的间距和格式。
    【解决方案2】:

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

    这里是Documentation link

    jsonObject.toString() // Produces json formatted object
    

    【讨论】:

    • 您可以发布异常详细信息吗?
    • 你在导入org.json.JSONObject 吗?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多