-3

My doubt is if there is any tool on-line or not to generate a string from a JSON. For example, I have this JSON:

  {
    "my_json": [
      {
        "number": 20,
        "name": "androider",
      },
      {
        "id": 3432,
        "name": "other_name",
      }
    ]
  }

If I want to declare a String in my code with this values, so I have to write many quotation marks to have my JSON in a String acceptable format.

So I want to know if thre is some tool to generate this String?

Avadhani Y
  • 7,566
  • 19
  • 63
  • 90
androidevil
  • 9,011
  • 14
  • 41
  • 79

4 Answers4

1

Some good choices are:

They have built in methods to do just whatever you need to do in an efficient way...

Jose-Rdz
  • 539
  • 6
  • 14
1

I can't quite tell what you want from your original question, but I assume you are trying to output a Java String that contains some JSON that you have generated.

You should use JSONObject and JSONArray to accomplish this.

To create this JSON:

{
    "my_json": [
      {
        "number": 20,
        "name": "androider",
      },
      {
        "id": 3432,
        "name": "other_name",
      }
    ]
}

You should use this code:

JSONObject a = new JSONObject();
a.put("number", 20);
a.put("name", "androider");

JSONObject b = new JSONObject();
b.put("id", 3432);
b.put("name", "other_name");

JSONArray array = new JSONArray();
array.put(a);
array.put(b);

JSONObject root = new JSONObject();
root.put("my_json", array);

// convert the root object to a string with 4 spaces of indentation
String json = root.toString(4);
Jschools
  • 2,698
  • 1
  • 17
  • 18
0

As told by Angel, Jackson and Gson are two cool libs. Gson is very easy to use while Jackson has better performance.

Popeye
  • 1,548
  • 3
  • 25
  • 39
0

Try here, Go through the answers mentioned below How to convert String to JSONObject in Java

in short,

Using org.json library:

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");

Here put your own string.

Edit: Try here, http://www.mkyong.com/java/json-simple-example-read-and-write-json/ Create a Json object, JSONObject jsonobj = new JSONObject(); Put your data using... josnobj.put()

Community
  • 1
  • 1
surender8388
  • 474
  • 3
  • 12
  • Pretty simple dude, follow this link, read for just 5 mini, you will get the thing in one shot. http://www.mkyong.com/java/json-simple-example-read-and-write-json/ – surender8388 Apr 18 '13 at 05:12