Can anybody tell me how to create JSON data in java code itself and toast it in android?
2 Answers
You can create a JSONObject from any string you like:
JSONObject js = new JSONObject(jsonString);
Where jsonString is, well, a json string like {name : 'Mark', id: '2'} or something more complicated.
You can also create an empty JSONObject and add the key-value pairs one by one:
JSONObject js = new JSONObject();
js.put("name", value); //where value can be anything
You should read more about JSONObject.
2 Comments
In your build.gradle file inside the module-leve (app), add the following:
dependencies {
compile 'com.google.code.gson:gson:2.3
}
Once you are done adding and syncing the project, simple create a simple java class that represent your json like this:
public class Book{
private String title;
private int pages;
private String author;
public Book(String title, int pages, String author){
this.title = title;
this.pages = pages;
this.author = author;
}
//you can add your getters and setters here;
}
Now to generate your json String for this class object, simply do this:
Book book = new Book("Killing a Mockingbird", 400, "Greg Manning");
//now generate Json string here
String json = new Gson().toJson(book);
Now you have your json String to toast or do whatever you want with it!
I hope this helps you!