在.Net中将Url编码的表单数据转换为JSON的一些选项是什么

Dan*_*Dan 19 .net c# forms json .net-4.5

我有一个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
Run Code Online (Sandbox Code Playgroud)

漂亮版本:

Property1=A
Property2=B
Property3[0][SubProperty1]=a
Property3[0][SubProperty2]=b
Property3[1][SubProperty1]=c
Property3[1][SubProperty2]=d
Run Code Online (Sandbox Code Playgroud)

以上数据需要转换为以下JSON数据:

{
    Property1: "A",
    Property2: "B",
    Property3: [
        { SubProperty1: "a", SubProperty2: "b" },
        { SubProperty1: "c", SubProperty2: "d" }]
}
Run Code Online (Sandbox Code Playgroud)

题:

有没有能够做到这一点的免费工具?我一直无法找到自己,如果它们存在,我宁愿消耗它们,也不愿自己写一个,但如果是这样,我会的.

AC#/ .Net解决方案是首选.

Pet*_* O. 22

我编写了一个实用程序类来解析查询字符串和表单数据.它可以在:

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);
Run Code Online (Sandbox Code Playgroud)

请让我知道这对你有没有用.

  • 感谢分享!我会仔细看看.我无法相信我是第一个需要这样做的人.我很高兴我并不孤单. (2认同)

MUG*_*G4N 12

.NET Framework 4.5包含将URL编码的表单数据转换为JSON所需的一切.为此,您必须System.Web.Extension在C#项目中添加对命名空间的引用.之后,您可以使用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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

{
    "Property1":"A",
    "Property2":"B",
    "Property3[0][SubProperty1]":"a",
    "Property3[0][SubProperty2]":"b",
    "Property3[1][SubProperty1]":"c",
    "Property3[1][SubProperty2]":"d"
}
Run Code Online (Sandbox Code Playgroud)

注意:输出不包含换行符或任何格式

来源:如何将查询字符串转换为json字符串?

  • @ MUG4N我不是说不是.我只是说它对我没有好处.有效的JSON只是要求的一部分.我需要正确表示数据的有效JSON.不过,我很感激你的帮助. (2认同)