简体   繁体   中英

how to validate the json string in asp.net c#?

I have json string which will pass to the webservice to perform some action on it. My json string will b like this example:

{"ID":"2","Name":"Tom","data":"[22.3,23.4,21.5]"}

I want to validate the json string if I remove the , (coma):

{"ID":"2""Name":"Tom""data":"[22.3,23.4,21.5]"} 

From the json string so its return error message json is not in the correct format.

JSON.netJSONSharp允许您将JSON解析为对象,并且能够验证或至少捕获错误异常

Try

var dynamicObject = Json.Decode(jsonString);

And see if it raises an error.

You may need to install the DLL for this separately. I believe it is in the MVC library download.

http://msdn.microsoft.com/en-us/library/system.web.helpers.json%28v=vs.111%29.aspx

Maybe you can try creating the JSON with the function ToJSON()

List<MyObject> people = new List<MyObject>{
                   new MyObject{ID = 1, Name= "Tom", Data= "[22.3,23.4,21.5]"},
                   new Person{ID = 2, Name= "Tome", LastName = ""[22.3,23.4,21.5]"}
                   };


string jsonString = people.ToJSON();

And if you with have the string as JSON you can do something like:

JsonConvert.SerializeObject(jsonString ).Dump();

Or using the Networking JSON: http://james.newtonking.com/json

A working code snippet

public bool isValidJSON(String json) { try { JToken token = JObject.Parse(json); return true; } catch(Exception ex){ return false; } }

Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM