2012-05-23 17 views
13

tengo que pasar algunos parámetros al servidor que tengo que pasar por debajo de formato¿Cómo crear datos de formato JSON en android?

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

Entonces, ¿cómo se puede generar este formato en el androide.

Intenté esto usando As shown in example 5.3 pero está mostrando un error en obj.writeJSONString(out); esta línea. ¿Alguien puede ayudarme a resolver esto?

Gracias por adelantado

Respuesta

37

No es que aunque en absoluto, de salida que desea es JSONArray dentro JSONObject y JSONObject dentro de otro JSONObject. Por lo tanto, puedes crearlos por separado y luego armarlos juntos. como a continuación.

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

Salida-

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

Gracias su trabajo bien – Harish

+0

+1 Soy nuevo en el análisis JSON. Este claro ejemplo fue todo lo que necesité :-) – rockstar

+0

Esta es una maravillosa sugerencia ... – DJhon

6

Puede utilizar JSONObject y construir sus datos con él.

Aquí está el Documentation link

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

Tampoco funciona. – Harish

+0

¿Puedes publicar los detalles de la excepción? – ChristopheCVB

+0

¿Está importando 'org.json.JSONObject'? – ChristopheCVB

2

Hola primero que hay que crear clases separadas HttpUtil.java.See siguiendo el código

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

Este ejemplo es ayudar a que acaba de llamar a esta función Devolverá JSON como valor de cadena. Pruébalo

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