简体   繁体   中英

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.

There is an inbuilt method to convert a JSONObject to a String. Why don't you use that:

JSONObject json = new JSONObject();

json.toString();

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

您可以使用

JsonObject.getString("msg"); 

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)

Use This:

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

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

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

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();
JSONObject metadata = (JSONObject) data.get("map"); //for example
String jsonString = metadata.**toJSONString()**;

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);
JSONObject data = (JSONObject) data.get("map"); 
 //for example
String jsonString = data.toJSONString();
     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"));

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM