116
{
    "data": 
    {
        "map":
        {
            "allowNestedValues": true,
            "create": "2012-12-11 15:16:13",
            "title": "test201212110004",
            "transitions": []
        }
    },
    "msg": "success",
    "code": "0"
}

Above is a JsonObject, the data is a JsonObject.

How to convert it to a String like "msg":"success" as you know, i can't directly add a double quotes outside data's value.

sp00m
  • 47,968
  • 31
  • 142
  • 252
Jay Zhang
  • 1,195
  • 2
  • 7
  • 3
  • 3
    I can't get it... Could you rephrase and give (even non-working) code snippets illustrating what you're attempting to do? – sp00m Jul 15 '13 at 09:56
  • 4
    JsonObject.getString("msg"); – string.Empty Jul 15 '13 at 09:58
  • You can add doublequotes with a backslash `\"` if that´s what you want. Please add your problem/question! – Benjamin Schwalb Jul 15 '13 at 09:58
  • 1
    Is that an instance of `org.json.JSONObject`? If it is, you can simply call `toString()` method of `JSONObject` to get JSON text of the`JSONObject`. – Stanley Jul 15 '13 at 10:01
  • 3
    It looks like what people who land here 3+ years later are finding useful is not at all related to what was asked. And it also looks like the question is long past help at getting clarified. I believe the original question was that @JayZhang wanted to flatten the object, such that data was a string representation of its inner json value. It seems no one answered how to do that. Doing so years later would be unlikely to have any value to others. People are landing from searching for converting json to a string and getting mired in a confused Q&A session best deleted. – dlamblin Sep 26 '17 at 04:19
  • It isn't just, as @dlamblin pointed out, that people are "landing" here years later, it's that the question really didn't have a lot to do with JSON in the first place. Yes, it does appear the OP wanted to know how to "flatten" the contents of "msg", but that gets into all sorts of questions about quoting quotes and "how does the OP expect to parse this thing and turn it back into something useful." There are some built-in string transforms, but with the OP's silence, who knows which one would have been most appropriate. – Julie in Austin Sep 19 '18 at 19:01
  • Which library is this JSONObject from ? – MasterJoe Apr 20 '19 at 17:23

15 Answers15

212

There is a built-in method to convert a JSONObject to a String. Why don't you use that:

JSONObject json = new JSONObject();

json.toString();
Archmede
  • 1,592
  • 2
  • 20
  • 37
Tanu Garg
  • 3,007
  • 4
  • 21
  • 29
  • { "data": "{ "map": { "allowNestedValues": true, "pdId": 168543, "source": "" } }", "msg": "success", "code": "0" } – Jay Zhang Jul 15 '13 at 12:21
  • 4
    i'm getting \ \ \ slashes in response string. how to convert json object without getting \ \ \ slashes – Onkar Musale Apr 03 '19 at 04:53
  • @Onkar share your string sample along with code snippet. – Tanu Garg Apr 03 '19 at 05:25
  • similar to this thread. but unable to find answer. https://stackoverflow.com/q/16563579/8098322 – Onkar Musale Apr 03 '19 at 05:30
  • {"date":"2013/5/15"}. Are u using import org.json.JSONObject; its working fine for me. Share your exact sample. JSONObject json = new JSONObject(); try { json.put("date", "2013/5/15"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(json.toString()); – Tanu Garg Apr 03 '19 at 06:28
  • Is this the same for Java EE's JsonObject? – dko Apr 16 '21 at 02:41
25

You can use:

JSONObject jsonObject = new JSONObject();
jsonObject.toString();

And if you want to get a specific value, you can use:

jsonObject.getString("msg");

or Integer value

jsonObject.getInt("codeNum");

For long Integers

jsonObject.getLong("longNum");
sureshtechi
  • 145
  • 5
  • 15
Janiel Mac
  • 259
  • 3
  • 3
  • 1
    It is better to use jsonObject.optString("msg") and jsonObject.optInt("codeNum") because if you use getString() or getInt() and the msg or codeNum values are null it'll throw and error and stop the program. Only difference with the methods I have mentioned is they won't throw an error if the values are null. – User1 Aug 26 '20 at 09:00
9

you can use

JsonObject.getString("msg"); 
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
5

You can try Gson convertor, to get the exact conversion like json.stringify

val jsonString:String = jsonObject.toString()
val gson:Gson = GsonBuilder().setPrettyPrinting().create()
val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
val jsonInString:String= gson.toJson(json)
println(jsonInString)
Naveen Kumar
  • 141
  • 3
  • 11
4

JsonObject seems to be JSON-P API. If this is true, I would use JsonWritter to write JsonValue into StringWriter:

    JsonObjectBuilder pokemonBuilder = Json.createObjectBuilder();
    pokemonBuilder.add("name", "Pikachu");
    pokemonBuilder.add("type", "electric");
    pokemonBuilder.add("cp", 827);
    pokemonBuilder.add("evolve", true);
    JsonObject pokemon = pokemonBuilder.build();
    StringWriter sw = new StringWriter(128);
    try (JsonWriter jw = Json.createWriter(sw)) {
        jw.write(pokemon);
    }
    String pokemonStr = sw.toString();
Tomas Kraus
  • 466
  • 2
  • 6
3

Add a double quotes outside the brackets and replace double quotes inside the {} with \"

So: "{\"data\":{..... }"

OverZealous
  • 39,252
  • 15
  • 98
  • 100
NargesooTv
  • 837
  • 9
  • 15
2

Use This :

JSONObject json = new JSONObject();
JSONObject.valueToString(json.toString());
Arman
  • 51
  • 2
  • 9
1

Example of Model

public class Person {
    private String name;
    private String age;
// setter and getter
// toString method
}

Example of Service method

public String getPerson() {
        JSONObject returnObj = new JSONObject();
        Person person = new Person();
        person.setAge("24");
        person.setName("Fazal");
        returnObj.put("age", person.getAge());
        returnObj.put("name", person.getName());
        return returnObj.toString();
    }

Json in java dependency needed

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>{New_Version}</version>
</dependency>

You will get this type of JSON result enter image description here

Fazal Haroon
  • 845
  • 2
  • 10
  • 20
0
JSONObject metadata = (JSONObject) data.get("map"); //for example
String jsonString = metadata.**toJSONString()**;
  • JSONObject json= (JSONObject) JSONValue.parse(jsonData); JSONObject data = (JSONObject) json.get("data"); After you have parsed the json data, you need to access the data object later get "map" data to json string. – Hakan Anlamaz Apr 14 '17 at 13:50
0

just use ObjectMapper

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
//here more config opts...
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);
String carAsString = objectMapper.writeValueAsString(car);
vitalinvent
  • 433
  • 1
  • 5
  • 11
0
JSONObject data = (JSONObject) data.get("map"); 
 //for example
String jsonString = data.toJSONString();
Joel Wembo
  • 814
  • 6
  • 10
-2
     This should get all the values from the above JsonObject  
     System.out.println(jsonObj.get("msg"));
     System.out.println(jsonObj.get("code"));

     JsonObject obj= jsonObj.get("data").getAsJsonObject().get("map").getAsJsonObject();
     System.out.println(obj.get("allowNestedValues"));
     System.out.println(obj.get("create"));
     System.out.println(obj.get("title"));
     System.out.println(obj.get("transitions"));
pshetty
  • 3
  • 2
-2

You can use reliable library GSON

private static final Type DATA_TYPE_JSON = 
        new TypeToken<JSONObject>() {}.getType();           
JSONObject orderJSON = new JSONObject();
orderJSON.put("noOfLayers", "2");
orderJSON.put("baseMaterial", "mat");
System.out.println("JSON == "+orderJSON.toString());
String dataAsJson = new Gson().toJson(orderJSON, DATA_TYPE_JSON);
System.out.println("Value of dataAsJson == "+dataAsJson.toString());
String data = new Gson().toJson(dataAsJson);
System.out.println("Value of jsonString == "+data.toString());
Kavitha yadav
  • 555
  • 5
  • 5
-5
 var data= {"data": {"map":{"allowNestedValues": true,"create": "2012-12-11 15:16:13","title": "test201212110004","transitions": []}},"msg": "success","code": "0"}

o/p:

Object {data: Object, msg: "success", code: "0"}

Use JSON.stringify to convert entire data into string like below

var stringData = JSON.stringify(data);

o/p:

"{"data":{"map":{"allowNestedValues":true,"create":"2012-12-11 15:16:13","title":"test201212110004","transitions":[]}},"msg":"success","code":"0"}"

Use JSON.parse to convert entire string object into JSON Object like below

var orgdata = JSON.parse(stringData);

o/p:

Object {data: Object, msg: "success", code: "0"}
Manojkanth
  • 1,071
  • 11
  • 27
Raghava
  • 17
  • 2
-7

I think you need this :

Suppose you have Sample JSON like this :

{"ParamOne":"InnerParamOne":"InnerParamOneValue","InnerParamTwo":"InnerParamTwoValue","InnerParamThree":"InnerParamThreeValue","InnerParamFour":"InnerParamFourValue","InnerParamFive":"InnerParamFiveValue"}}

Converted to String :

String response = {\"ParamOne\":{\"InnerParamOne\":\"InnerParamOneValue\",\"InnerParamTwo\":\"InnerParamTwoValue\",\"InnerParamThree\":\"InnerParamThreeValue\",\"InnerParamFour\":\"InnerParamFourValue\",\"InnerParamFive\":\"InnerParamFiveValue\"}} ;

Just replace " by \"