当前位置:首页>开发>正文

如何在指定json字符串后拼接json字符串 如何将字符串装换成json格式

2023-04-12 13:13:40 互联网 未知 开发

 如何在指定json字符串后拼接json字符串 如何将字符串装换成json格式

如何在指定json字符串后拼接json字符串

可以使用NSDictionary中的键值对来拼接Json数据,非常方便,也可以进行嵌套,直接上代码:

//开始拼接Json字符串
NSDictionary *dataDictionary= [NSDictionary dictionaryWithObjectsAndKeys:@"mac",@"mac",
@"game",@"game",
@"devicetoken",@"devicetoken",
@"device",@"device",
@"gv",@"gv",
@"lang",@"lang",
@"os",@"os",nil]
NSDictionary *parmDictionary= [NSDictionary dictionaryWithObjectsAndKeys:@"getSession",@"act",
dataDictionary,@"data",nil]
NSDictionary *jsonDictionary=[NSDictionary dictionaryWithObjectsAndKeys:@"pv",@"pv",
parmDictionary,@"param",nil]
SBJsonWriter *writer = [[SBJsonWriter alloc] init]

NSString *jasonString = [writer stringWithObject:jsonDictionary]
NSLog(@"%@",jasonString)
上面的代码用到了三层嵌套,注意的是,NSDictionary中,前面的是值,后面的是键。
拼接后的结果如下:

{"pv":"pv","param":{"act":"getSession","data":{"os":"os","mac":"mac","game":"game","gv":"gv","lang":"lang","devicetoken":"devicetoken","device":"device"}}}
使用 Json在线校验工具 解析后:
{
"pv": "pv",
"param": {
"act": "getSession",
"data": {
"os": "os",
"mac": "mac",
"game": "game",
"gv": "gv",
"lang": "lang",
"devicetoken": "devicetoken",
"device": "device"
}
}
}

如何将字符串装换成json格式

引入jar包 json-lib-2.JSONObject jsonObject = JSONObject.fromObject("json格式的字符串")

String jsonStr = "{id:2}"JSONObject jsonObject = JSONObject.fromObject(jsonStr)int id = jsonObject.getInt("id")

java怎样进行json字符串拼接?

StringBuffer
利用StringBuffer来拼接和截取,如果是拼接字符串强烈建议使用StringBuffer。这样可以防止内存泄露,否则大量用Str=str1 str2,会造成内存溢出用法如图。

怎么将字串符转换为JSON格式

jQuery中使用jQuery.parseJSON()方法将字符串转为json格式 例如: jQuery.parseJSON({"test":1})注意: 传入格式有误的 JSON 字符串可能导致抛出异常。

怎么自己拼接一个json格式

方法,整个json串是一个list或者Map,然后Map中又可以添加Map,也可以添加List ,如此层层添加即可。
因此,只使用List和Map操作,就可以拼接任意固定格式的Json字符串。
java代码:
String inputJson = ""Map inputMap = new HashMap()
// userMap userMap = new HashMap()userMap.put("loginName", "))userMap.put("loginPassword","))inputMap.put("userInfo", userMap)
// dataMap bussdataMap = new HashMap()bussdataMap.put("tableName", "")List dataList = new ArrayList()Map dataMap = new HashMap()
// dataMap.put("id", "")dataMap.put("id_card_no","" )dataList.add(dataMap)bussdataMap.put("row", dataList)inputMap.put("dataInfo", bussdataMap)
// operationTypeinputMap.put("operate", "插入")JSONWriter writer = new JSONWriter(false)inputJson = writer.write(inputMap)

最新文章