在.Net中将URL编码的表单数据转换为JSON有哪些选项

nuypyhwy  于 2023-05-08  发布在  .NET
关注(0)|答案(3)|浏览(175)

我有一个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" }]
}

问题:

有没有免费的工具可以做到这一点?我自己还没有找到,如果它们存在,我宁愿消费它们而不是自己写一个,但如果它来了,我会的。
C#/.NET解决方案是首选。

k97glaaz

k97glaaz1#

我编写了一个实用程序类,用于解析查询字符串和表单数据。可在以下网址获得:
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);

告诉我你是否适合。

wdebmtf2

wdebmtf22#

.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"
}
s3fp2yjn

s3fp2yjn3#

如果你使用的是ASP.NET Core 1.0+和JSON.NET,你可以这样做:

var reader = new Microsoft.AspNetCore.WebUtilities.FormReader(httpRequest.Body, Encoding.UTF8);
Dictionary<string, StringValues> keyValuePairs = await reader.ReadFormAsync();
var json = JsonConvert.SerializeObject(keyValuePairs);

相关问题