![](/img/trans.png)
[英]How can I convert url-encoded or url-decoded string to json format and then to object?
[英]What Are Some Options To Convert Url-Encoded Form Data to JSON in .Net
我有一個Web請求,它發送的服務器數據格式為application/x-www-form-urlencoded
。 我想將它轉換為application/json
。
例:
URL編碼的表單數據:
Property1=A&Property2=B&Property3%5B0%5D%5BSubProperty1%5D=a&Property3%5B0%5D%5BSubProperty2%5D=b&Property3%5B1%5D%5BSubProperty1%5D=c&Property3%5B1%5D%5BSubProperty2%5D=d
漂亮版本:
Property1=A
Property2=B
Property3[0][SubProperty1]=a
Property3[0][SubProperty2]=b
Property3[1][SubProperty1]=c
Property3[1][SubProperty2]=d
以上數據需要轉換為以下JSON數據:
{
Property1: "A",
Property2: "B",
Property3: [
{ SubProperty1: "a", SubProperty2: "b" },
{ SubProperty1: "c", SubProperty2: "d" }]
}
題:
有沒有能夠做到這一點的免費工具? 我一直無法找到自己,如果它們存在,我寧願消耗它們,也不願自己寫一個,但如果是這樣,我會的。
AC#/ .Net解決方案是首選。
我編寫了一個實用程序類來解析查詢字符串和表單數據。 它可以在:
https://gist.github.com/peteroupc/5619864
例:
// Example query string from the question
String test="Property1=A&Property2=B&Property3%5B0%5D%5BSubProperty1%5D=a&Property3%5B0%5D%5BSubProperty2%5D=b&Property3%5B1%5D%5BSubProperty1%5D=c&Property3%5B1%5D%5BSubProperty2%5D=d";
// Convert the query string to a JSON-friendly dictionary
var o=QueryStringHelper.QueryStringToDict(test);
// Convert the dictionary to a JSON string using the JSON.NET
// library <http://json.codeplex.com/>
var json=JsonConvert.SerializeObject(o);
// Output the JSON string to the console
Console.WriteLine(json);
請讓我知道這對你有沒有用。
.NET Framework 4.5包含將URL編碼的表單數據轉換為JSON所需的一切。 為此,您必須在C#項目中添加對命名空間System.Web.Extension
的引用。 之后,您可以使用JavaScriptSerializer
類,它為您提供進行轉換所需的一切。
代碼
using System.Web;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var dict = HttpUtility.ParseQueryString("Property1=A&Property2=B&Property3%5B0%5D%5BSubProperty1%5D=a&Property3%5B0%5D%5BSubProperty2%5D=b&Property3%5B1%5D%5BSubProperty1%5D=c&Property3%5B1%5D%5BSubProperty2%5D=d");
var json = new JavaScriptSerializer().Serialize(
dict.Keys.Cast<string>()
.ToDictionary(k => k, k => dict[k]));
Console.WriteLine(json);
Console.ReadLine();
}
}
}
輸出
{
"Property1":"A",
"Property2":"B",
"Property3[0][SubProperty1]":"a",
"Property3[0][SubProperty2]":"b",
"Property3[1][SubProperty1]":"c",
"Property3[1][SubProperty2]":"d"
}
注意:輸出不包含換行符或任何格式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.