How to serialize Object to JSON?

前端 未结 7 1672
面向向阳花
面向向阳花 2020-11-27 05:49

I need to serialize some objects to a JSON and send to a WebService. How can I do it using the org.json library? Or I\'ll have to use another one? Here is the class I need t

7条回答
  •  迷失自我
    2020-11-27 06:08

    You make the http request

    HttpResponse response = httpclient.execute(httpget);           
    HttpEntity entity = response.getEntity();
    
    inputStream = entity.getContent();
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
    

    You read the Buffer

    String line = null;
    while ((line = reader.readLine()) != null)
    {
    sb.append(line + "\n");
    }
    Log.d("Result", sb.toString());
    result = sb.toString();
    

    Create a JSONObject and pass the result string to the constructor:

    JSONObject json = new JSONObject(result);
    

    Parse the json results to your desired variables:

    String usuario= json.getString("usuario");
    int idperon = json.getInt("idperson");
    String nombre = json.getString("nombre");
    

    Do not forget to import:

    import org.json.JSONObject;
    

提交回复
热议问题