-3

I want to get a JSON String from the created JSONObject, which looks like a String when you want to create a JSONObject from that String.

I can write a method, I just cannot believe there isn't have a better solution.

import org.json.JSONObject;

public class JSONString {

    JSONObject jsonObject = new JSONObject();
    jsonObject.append("symbol", "AAPL");
    jsonObject.append("price", "211.17");

    // this is the String what I want to get from the jsonObject variable
    String wantedResultString = "{\n" +
                "  \"symbol\" : \"AAPL\",\n" +
                "  \"price\" : 211.17\n" +
                "}";


}

3 Answers3

0

You can try this:

String jsonObjectString = jsonObject.toString();
Dino
  • 7,779
  • 12
  • 46
  • 85
Ibrahim Lawal
  • 1,168
  • 16
  • 31
0

try this

JSONObject jsonObject = new JSONObject();
        jsonObject.put("symbol", "AAPL");
        jsonObject.put("price", 211.17);
        System.out.println(jsonObject);
0

Use put() instead of append()and the use jsonObject.toString()

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;
public class Test {
    public static void main(String[] args) throws IOException, JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("symbol", "AAPL");
        jsonObject.put("price", "211.17");
        System.out.println(jsonObject.toString());
    }

}

output:

{"symbol":"AAPL","price":"211.17"}
madhepurian
  • 271
  • 1
  • 13