Jay Zhang
Jay Zhang

Reputation: 1235

Convert JsonObject to String

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

Upvotes: 120

Views: 704976

Answers (15)

Tanu Garg
Tanu Garg

Reputation: 3067

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

Upvotes: 218

Fazal Haroon
Fazal Haroon

Reputation: 1193

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

Upvotes: 1

Joel Wembo
Joel Wembo

Reputation: 900

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

Upvotes: 0

Janiel Mac
Janiel Mac

Reputation: 269

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

Upvotes: 26

Arman
Arman

Reputation: 51

Use This :

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

Upvotes: 2

vitalinvent
vitalinvent

Reputation: 493

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

Upvotes: 0

Tomas Kraus
Tomas Kraus

Reputation: 446

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

Upvotes: 4

Naveen Kumar
Naveen Kumar

Reputation: 171

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)

Upvotes: 5

Kavitha yadav
Kavitha yadav

Reputation: 635

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

Upvotes: -2

Raghava
Raghava

Reputation: 17

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

Upvotes: -5

Hakan Anlamaz
Hakan Anlamaz

Reputation: 61

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

Upvotes: 0

pshetty
pshetty

Reputation: 3

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

Upvotes: -2

NargesooTv
NargesooTv

Reputation: 907

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

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

Upvotes: 3

Vivek Adhikari
Vivek Adhikari

Reputation: 15

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

Upvotes: -7

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

you can use

JsonObject.getString("msg"); 

Upvotes: 9

Related Questions