2012-05-23 40 views
13

Ben formatında android bu biçimi üretebilir olmasi çokAndroid'de JSON biçim verileri nasıl oluşturulur?

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

aşağıdaki gibi geçmesi gerekiyor sunucuya bazı parametreleri geçmesi gerekiyor.

Bu satırı As shown in example 5.3 kullanarak denedim, ancak bu satır obj.writeJSONString(out); hata gösteriyor. Bunu çözmede yardımcı olabilecek herhangi biri olabilir.

Teşekkür peşin

cevap

37

it'i değildir. Böylece, onları ayrı ayrı oluşturabilir ve sonra bir araya getirebilirsiniz. aşağıda olduğu gibi.

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

Çıkış-

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

Çalışanın iyi çalıştığına teşekkürler. – Harish

+0

+1 JSON ayrıştırma konusunda yeni. Bu açık örnek, tüm ihtiyacım olan şeydi :-) – rockstar

+0

Bu harika bir öneri ... – DJhon

6

You JSONObject kullanabilir ve onunla verilerinizi inşa. İşte

hiç rağmen, istediğiniz çıkışı başka JSONObject nesnesi içindeki JSONObject nesnesi ve JSONObject nesnesi içindeki JSONArray olduğunu Documentation link

jsonObject.toString() // Produces json formatted object 
+0

Ayrıca çalışmıyor. – Harish

+0

İstisna ayrıntılarını gönderir misiniz? – ChristopheCVB

+0

'org.json.JSONObject' öğesini mi kullanıyorsunuz? – ChristopheCVB

2

Merhaba öncelikle size sadece bu fonksiyonu çağırmak yardımcı kod

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

Bu örnekte, aşağıdaki ayrı sınıf HttpUtil.java.See oluşturmak olduğunu var JSON, dize değeri olarak dönecektir .. Deneyin

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