How to create a Json object

I have a database that has three coloums (id (integer), startdate (text), enddate (text)). I want to read all the entries for these coloums, convert them to Json, and submit to the website. I know how to read values, but did not know how to make Json from these values. Please any help on coding ...

+4
source share
4 answers

Why don't you try:
`

JSONObject object = new JSONObject(); try { object.put("id", id); object.put("startDate", startDate); object.put("endDate", endDate); } catch (JSONException e) { e.printStackTrace(); }` 

Then send json object via http message
`

 HttpClient hc = new DefaultHttpClient(); String message; HttpPost p = new HttpPost(url); try { message = object.toString(); p.setEntity(new StringEntity(message, "UTF8")); p.setHeader("Content-type", "application/json"); HttpResponse resp = hc.execute(p); if (resp != null) { if (resp.getStatusLine().getStatusCode() == 204) result = true; } Log.d("Status line", "" + resp.getStatusLine().getStatusCode()); } catch (Exception e) { e.printStackTrace(); }` 

so if you want to create a JSON object containing all the triplets you get from SQLite db, this will be:

 String query = "SELECT *"+ "from "+TABLE_NAME; Cursor c = db.rawQuery(query,new String[]{}); Log.d("query",query); c.moveToFirst(); while(c.moveToNext()){ try { int id = c.getInt(c.getColumnIndex("ID")); String startDate = c.getString(c.getColumnIndex("START_DATE")); String endDate = c.getString(c.getColumnIndex("END_DATE")); object.put("id", id); object.put("startDate", startDate); object.put("endDate", endDate); }} 

where ID, START_DATE and END_DATE are the corresponding field names in the database.
I canโ€™t check my code right now, but I believe that it works

+3
source

Here's how to create a JSON object:

 JSONObject jsonObject = new JSONObject(); jsonObject.put("id", idValue); jsonObject.put("startDate", endDateValue); jsonObject.put("endDate", endDateValue); 

You can also get JSON as a String by doing:

 jsonObject.toString(); 
+3
source
  JSONObject json = new JSONObject(); json.put("id", id); json.put("startdate", startdate); json.put("enddate", enddate); 
0
source

Using the jackson library, you can convert a map or java bean to a json string or create a map or javabean from a json string. you can write util class:

  public class JsonUtil { private static final ObjectMapper MAPPER = new ObjectMapper(); public static String convertToJsonStr(Object model) throws IOException { return MAPPER.writeValueAsString(model); } @SuppressWarnings("unchecked") public static Map<String, Object> readFromStr(String content) throws IOException { return readFromStr(content, Map.class); } public static <T> T readFromStr(String content, Class<T> clazz) throws IOException { return MAPPER.readValue(content, clazz); } } 
0
source

All Articles