将JsonObject转换为String


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

以上是一个JsonObjectdata是一个JsonObject

如您所知,如何将其转换为String类似的值"msg":"success",我无法在data的值外直接添加双引号。


3
我听不清...您能改写并给出(甚至是无效的)代码段来说明您尝试执行的操作吗?
sp00m

4
JsonObject.getString(“ msg”);
Nicolas Tyler

如果需要的话,可以在双引号后面加上反斜杠\"。请添加您的问题/问题!
本杰明·施瓦布

1
那是的实例org.json.JSONObject吗?如果是,则只需调用toString()方法JSONObject即可获取的JSON文本JSONObject
斯坦利

3
看起来3年后来到这里的人们发现有用的东西根本与所要求的无关。而且看起来这个问题早已为澄清问题所用。我相信最初的问题是@JayZhang要展平对象,以便数据是其内部json值的字符串表示形式。似乎没有人回答如何做。多年以后再这样做对其他人没有任何价值。人们正在寻找将json转换为字符串并陷入混乱的Q&A会话中的最佳方式。
dlamblin

Answers:


153

有一个内置方法可以将JSONObject转换为String。您为什么不使用它:

JSONObject json = new JSONObject();

json.toString();

{“ data”:“ {” map“:{” allowNestedValues“:true,” pdId“:168543,” source“:”“}}}”,“ msg”:“成功”,“ code”:“ 0”}
周杰伦张

我在响应字符串中得到\ \ \斜线。如何在不得到\ \ \斜杠的情况下转换json对象
Onkar Musale '19

@Onkar与代码段共享您的字符串示例。
Tanu Garg,

与此线程类似。但找不到答案。stackoverflow.com/q/16563579/8098322
Onkar Musale,

{“ date”:“ 2013/5/15”}。您是否使用import org.json.JSONObject; 它对我来说很好。分享您的确切样本。JSONObject json =新的JSONObject(); 试试{json.put(“ date”,“ 2013/5/15”); } catch(JSONException e){// TODO自动生成的catch块e.printStackTrace(); } System.out.println(json.toString());
Tanu Garg,

13

您可以使用:

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

如果要获取特定值,可以使用:

jsonObject.getString("msg");

或整数值

jsonObject.getInt("codeNum");

最好使用jsonObject.optString(“ msg”)和jsonObject.optInt(“ codeNum”),因为如果您使用getString()或getInt()并且msg或codeNum值为null,它将抛出并出错并停止程序。与我提到的方法唯一的区别是,如果值为null,则它们不会引发错误。
User1


2

您可以尝试Gson转换器,以获得确切的转换,例如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)

1

在方括号内添加双引号,并在内将双引号替换{}\"

所以: "{\"data\":{..... }"


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”); 解析json数据后,您需要访问数据对象,稍后将“映射”数据映射到json字符串。
哈坎·阿拉马兹

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

这不能回答问题。
ralfe

-2

您可以使用可靠的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());

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

使用JSON.stringify将整个数据转换为如下所示的字符串

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

使用JSON.parse将整个字符串对象转换为JSON对象,如下所示

var orgdata = JSON.parse(stringData);

o / p:

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

-6

我认为您需要这个:

假设您有这样的Sample JSON

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

转换为String:

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

只需将“替换为”

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.