Can anybody tell me how to create JSON data in java code itself and toast it in android?
Asked
Active
Viewed 183 times
2 Answers
3
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.

Vucko
- 7,371
- 2
- 27
- 45
-
Yes , that works thank you. – Vaibhav Kadam Jun 15 '16 at 08:48
-
No problem. I know it does. This should be a closed question tho because you could've googled this yourself, but I decided to give you a short answer anyway. Consider accepting the answer in order to close the question please. – Vucko Jun 15 '16 at 08:50
2
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!

Eenvincible
- 5,641
- 2
- 27
- 46
-
Gson is always the viable solution, and a good one too, but I tried to make it as simple as possible :) – Vucko Jun 15 '16 at 08:53