本文介绍了如何在C#中取消json字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在c#中取消激活json字符串。

i取相应json元素的值并获得以下异常:



传入的对象无效,':'或'}'期望json序列化c#



我尝试过:



构建Json代码如下:

How to deselarize a json string in c#.
i am taking the values for the respective json elements and getting exception below:

Invalid object passed in, ':' or '}' expected json serialize c#

What I have tried:

Building Json Code as below:

 string json = @"
   [
    {

        {
        ""bankId"": """ + hsk.bankid + @""",
        ""password"": """ + hsk.password + @"""
        }


 }
]
";



输出

$ /


Output

   [
    {

        {
        "bankId": "011",
        "password": "test123"
        }


 }
]

Deserializing as below:
<pre>   HandShakeRequest resultT = new JavaScriptSerializer().Deserialize<HandShakeRequest>(json);

推荐答案

[{"bankId":"011","password":"test123"}]

但是......纯文本密码?不是一个好主意... []

切勿以明文形式存储密码 - 这是一个主要的安全风险。有关如何在此处执行此操作的信息: []

But ... plain text passwords? Not a good idea ... Code Crime 1[^]
Never store passwords in clear text - it is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^]


引用:

[

{



{

bankId:011,

password:test123

}





}

]

[
{

{
"bankId": "011",
"password": "test123"
}


}
]





这是一个无效的JSON字符串。您可以使用,例如 []。另请参阅 []。



That is an invalid JSON string. You may check it using, for instance JSONLint[^]. See also JSON Objects at w3schools[^].


public static bool IsValidJson(string strInput)
        {
            strInput = strInput.Trim();
            if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
                (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
            {
                try
                {
                    var obj = JToken.Parse(strInput);
                    return true;
                }
                catch (JsonReaderException jex)
                {
                    //Exception in parsing json
                    //jex.Message;
                    return false;
                }
                catch (Exception ex) //some other exception
                {
                    //ex.ToString()
                    return false;
                }
            }
            else
            {
                return false;
            }
        }





您可以这样做:





You can then do:

var isValid = IsValidJson(jsonString);

if(isValid){
   //deserialize here
}





另请注意所述的安全风险由OriginalGriff。



Also keep note of the security risk as stated by OriginalGriff.


这篇关于如何在C#中取消json字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:31