我在C#工作。在这里,我经常需要将用C#编写的Json转换为常规字符串格式,就像这个C#字符串一样
"{" +
"\"grant_type\": \"password\"," +
"\"client_id\": 2," +
"\"client_secret\": \"ClientSecretHere\"," +
"\"username\": \"abc@company.com\"," +
"\"password\": \"somepassword\" " +
"}";
其常规字符串等效
"{
"grant_type": "password",
"client_id": 2,
"client_secret":"ClientSecretHere",
"username": "abc@company.com",
"password": "somepassword"
}"
我在互联网上搜索了很多,但每个人都在谈论从Json到C#或C#到json的转换。对此有什么好的程序化解决方案吗?
答案 0 :(得分:2)
您的“c#字符串”无效。但无论如何,这可能只是一个不好的例子,在构建到“c#string”之前的过程可能是某种限制。 Anywho - 让我们试一试:
using Netwonsoft.Json.Linq;
...
var text = "{" +
"\"grant_type\": \"password\"," +
"\"client_id\": 2," +
"\"client_secret\": \"ClientSecretHere\"," +
"\"username\": \"abc@company.com\"," +
"\"password\": \"somepassword\"
}";
var token = JToken.Parse(text);
var json = JObject.Parse((string)token);
Console.WriteLine(json);
应该为您提供“常规字符串等效”。如果这不起作用,也许对象反序列化将:
using Newtonsoft.Json;
...
var text = "{" +
"\"grant_type\": \"password\"," +
"\"client_id\": 2," +
"\"client_secret\": \"ClientSecretHere\"," +
"\"username\": \"abc@company.com\"," +
"\"password\": \"somepassword\"
}";
var json = JsonConvert.DeserializeObject(text);
Console.WriteLine(json);