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 = new JSONObject();
object1.put("param1", "value1");
object1.put("param2", "param2");
JSONObject innerObject1 = new JSONObject();
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 {
JSONObject object=new JSONObject();
object.put("param1","value1");
object.put("param2","value2");
JSONObject param3=new JSONObject();
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
public class Response {
public String param1;
public String param2;
public Param3 param3;
public Response(String param1, String param2) {
this.param1 = param1;
this.param2 = param2;
}
public class Param3 {
public String username;
public String password;
public Param3(String username, String password) {
this.username = username;
this.password = password;
}
}
}
In file in which you insert data
Response res = new Response("value1", "value2", new Param3("admin","123"));
String dbResult = new Gson.toJson(res);
Post a Comment for "How To Generate JSON Stringer In Android For This Format"