John
John

Reputation: 1407

Convert a set of String values to JSON object in Android

I have string values I just want to convert all the values in json format

I have tried is coming only key and value format

JSONObject defaul = guard.getJSONObject("default");
defaul.put("security_id", Helper.loadSavedPreferences(getApplicationContext(), "security_id"));
defaul.put("location", work_location);
defaul.put("type_of_service", type_of_service);
defaul.put("type_of_service", type_of_service);
defaul.put("log_date", date);`

I want the json format like below

{
"sample": {
    "0": {
        "time": "5.00PM",
        "occurence": "fsdfdsfsdfdsfsdf sdfsdfsdfsdf sdsdfsdf",
        "sir_ref": "dsfsdf5"
    },
    "1": {
        "time": "6.00AM",
        "occurence": "fsdfdsfsdfdsfsdf sdfsdfsdfsdf sdsdfsdf",
        "sir_ref": "dsfsdf5"
    },
    "default": {
        "security_id": "id",
        "location": "location",
        "type_of_service": "S",
        "log_date": "2014-07-20",
        "log_day": "monday",
        "log_st_time": "10.00AM",
        "log_end_time": "10.00AM",
        "name": "xyz",
        "signature": "xyz",
        "licence_no": "A12456asd",
        "dog_name": "Puppy",
        "id_card_no": "2342343243d",
        "coc_no": "fsdfsdfs23"
    },
    "crib": {
        "crib_st_time1": "10.00AM",
        "crib_end_time1": "10.00AM",
        "crib_st_time2": "10.00AM",
        "crib_end_time2": "10.00AM"
    }
},
"msg": "Success"
}

can any one help to solve this problem.

Upvotes: 0

Views: 1592

Answers (2)

Lal
Lal

Reputation: 14810

See this link for more details.

Try this

JSONObject obj = new JSONObject();
  LinkedHashMap m1 = new LinkedHashMap();
  LinkedList l1 = new LinkedList();
  obj.put("k1", "v1");
  obj.put("k2", m1);
  obj.put("k3", l1);
  m1.put("mk1", "mv1");
  l1.add("lv1");
  l1.add("lv2");
  m1.put("mk2", l1);

  obj.writeJSONString(out);
  System.out.println("jsonString:");
  System.out.println(out.toString());
  String jsonString = obj.toJSONString();
  System.out.println(jsonString);

This returns a string as follows

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

Upvotes: 0

Alécio Carvalho
Alécio Carvalho

Reputation: 13657

You can use Gson it helps you working with JSON in several ways...an example is you put your values into a Map and do the following:

  Map<String, String> valuesMap = new HashMap<String, String>();
  valuesMap.put("key1", "value1");
  valuesMap.put("key2", "value2");

 Gson gson = new GsonBuilder().create();
 String json = gson.toJson(valuesMap);

 System.out.println(json);

It will give the following output in JSON format:

 {"key1":"value1","key2":"value2"}

NOTE: Gson is so powerful that you're not limited to Map, you can also use your own complex objects (ValueObjects e.g. JavaBeans) and it will handle it.

Upvotes: 3

Related Questions