json文本反转义代码

DaveBoy 2024/6/25 发布 · 2024/6/25 更新 · 488 次阅读

json格式化 动作中需要将json中转义后的内容反转义并进行格式化展示,其中包含json遍历、json类型判断、json反转义处理、json替换,实现代码如下

$= 
var token = JToken.Parse({afterDealText});

var settings = new JsonSerializerSettings();
settings.Error = (sender, args) => {
    args.ErrorContext.Handled = true;
};


var tokenList=new List<JToken>();
var tokenPath=new List<String>();
tokenList.Add(token);
tokenPath.Add("$");
while(tokenList.Count()>0){
	JToken curToken=tokenList[tokenList.Count()-1];
	tokenList.RemoveAt(tokenList.Count()-1);
	string curPath=tokenPath[tokenPath.Count()-1];
	tokenPath.RemoveAt(tokenPath.Count()-1);

	if (curToken.Type == JTokenType.Object) {
	    var tokenDict = curToken.ToDictionary();
	    var keys = tokenDict.Keys.ToList();
	    for (int i = 0; i < keys.Count; i++) {
	        var value = curToken[keys[i]];
			if (value.Type== JTokenType.Object||value.Type== JTokenType.String||value.Type== JTokenType.Array) {
	        	tokenList.Add((JToken)value);
	            tokenPath.Add(curPath+"."+keys[i]);
	        }
	    }

	} else if(curToken.Type == JTokenType.Array){
		var tokenlist = curToken.ToList();
		var count=tokenlist.Count();
	    for (int i = 0; i < count; i++) {
	    	var value = tokenlist[i];
			if (value.Type== JTokenType.Object||value.Type== JTokenType.String||value.Type== JTokenType.Array) {
	        	tokenList.Add((JToken)value);
	            tokenPath.Add(curPath+"["+i+"]");
	        }
	    }
	} else if(curToken.Type == JTokenType.String){
		var strValue = (string)curToken;
        var jsonValue = JsonConvert.DeserializeObject<JToken>(strValue, settings);
        if (jsonValue != null &&(jsonValue.Type == JTokenType.Object||jsonValue.Type == JTokenType.Array)) {
            var path=curPath;
        	var select = token.SelectToken(path);
            select.Replace((JToken)jsonValue);
            tokenList.Add(jsonValue);
            tokenPath.Add(path);
        }
	}
}

return token;
· {{comment.createTimeStr}}
{{reply.votePoints}}
回复   – {{reply.createTimeStr}}
回复 x
标签
目录
相关操作