1

Can anybody tell me how to create JSON data in java code itself and toast it in android?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes , that works thank you.
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.
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!

1 Comment

Gson is always the viable solution, and a good one too, but I tried to make it as simple as possible :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.