可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
{ "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.
回答1:
@hsz we have inbuild method to convert jsonObject to string. Why don't you use that.
JSONObject json = new JSONObject(); json.toString();
回答2:
you can use
JsonObject.getString("msg");
回答3:
Add a double quotes outside the brackets and replace double quotes inside the {}
with \"
So: "{\"data\":{..... }"
回答4:
JSONObject metadata = (JSONObject) data.get("map"); //for example String jsonString = metadata.**toJSONString()**;
回答5:
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"));
回答6:
You can use reliable library GSON
private static final Type DATA_TYPE_JSON = new TypeToken() {}.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());
回答7:
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"}
回答8:
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 \"