121
{
    "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.

7
  • 3
    I can't get it... Could you rephrase and give (even non-working) code snippets illustrating what you're attempting to do? Commented Jul 15, 2013 at 9:56
  • 4
    JsonObject.getString("msg"); Commented Jul 15, 2013 at 9:58
  • You can add doublequotes with a backslash \" if that´s what you want. Please add your problem/question! Commented Jul 15, 2013 at 9: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 theJSONObject. Commented Jul 15, 2013 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. Commented Sep 26, 2017 at 4:19

15 Answers 15

218

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();
Sign up to request clarification or add additional context in comments.

6 Comments

{ "data": "{ "map": { "allowNestedValues": true, "pdId": 168543, "source": "" } }", "msg": "success", "code": "0" }
i'm getting \ \ \ slashes in response string. how to convert json object without getting \ \ \ slashes
@Onkar share your string sample along with code snippet.
similar to this thread. but unable to find answer. stackoverflow.com/q/16563579/8098322
{"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());
|
27

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");

1 Comment

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.
9

you can use

JsonObject.getString("msg"); 

Comments

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)

Comments

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();

Comments

3

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

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

Comments

2

Use This :

JSONObject json = new JSONObject();
JSONObject.valueToString(json.toString());

1 Comment

JsonObject =/= JSONObject
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

Comments

0
JSONObject metadata = (JSONObject) data.get("map"); //for example
String jsonString = metadata.**toJSONString()**;

1 Comment

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.
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);

Comments

0
JSONObject data = (JSONObject) data.get("map"); 
 //for example
String jsonString = data.toJSONString();

Comments

-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"));

1 Comment

this doesn't answer the question.
-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());

Comments

-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"}

Comments

-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 \"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.