Skip to content Skip to sidebar Skip to footer

How To Generate Json Stringer In Android For This Format

I need to send data to database in this format - {'param1':'value1', 'param2':'value2', 'param3': {'username': 'admin', 'password': '123'}} How to generate this using JSONStringe

Solution 1:

JSONObject object1 = newJSONObject();

object1.put("param1", "value1");
object1.put("param2", "param2");

JSONObject innerObject1 = newJSONObject();
innerObject1.put("username", "admin");
innerObject1.put("password", "123");

object1.put("param3",innerObject1);

String jsonStr = object1.toString();

Ideally reverse of JSON parsing can be applied to create a json string object, so that the same can be send to Server/DB

Solution 2:

Try this

try {
        JSONObjectobject=newJSONObject();
        object.put("param1","value1");
        object.put("param2","value2");
        JSONObject param3=newJSONObject();
        paraam3.put("username","admin");
        paraam3.put("password","123");
        object.put("param3",param3);
    } catch (JSONException e) {
        e.printStackTrace();
    }

Solution 3:

You can create model which will be your java file same as your JSON file and can use gson library which is supported by Google to do JSON parsing. The library is quite flexible and easy to use then using traditional method of JSON parsing.

Model File

publicclassResponse {
publicString param1;
publicString param2;
publicParam3 param3;
publicResponse(String param1, String param2) {
    this.param1 = param1;
    this.param2 = param2;
}
      publicclassParam3 {
            publicString username;
            publicString password;

    publicParam3(String username, String password) {
        this.username = username;
        this.password = password;
    }
      }
}

In file in which you insert data

Responseres=newResponse("value1", "value2", newParam3("admin","123"));
StringdbResult=newGson.toJson(res);

Post a Comment for "How To Generate Json Stringer In Android For This Format"