[英]Add quotes to a string to make it JSON in C#
我正在使用使用 JSON 格式的服务。
但是我从哪里得到 JSON 不包含围绕键和值的双引号。
这是我拥有的数据示例
[{name:{buyerfirstname:Randy, buyermiddlename:null, buyerlastname:Johnson}, buyerfullname:Randy Johnson, businessname:null}]
我如何在 C# 中将其转换为 JSON
注意:null 不应包含双引号
所以,我在玩弄你的字符串,并根据你的字符串格式不正确的评论,所以我设计了一种使用Regular Expressions
的方法来解析有问题的字符串中的数据。 请在下面找到我的尝试和一个工作示例的代码: https : //dotnetfiddle.net/XLSde4
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string str = "[{name:{buyerfirstname:Randy, buyermiddlename:null, buyerlastname:Johnson}, buyerfullname:Randy Johnson, businessname:null}]";
showMatch(str, @"(?<=[:,])(.*?)(?=\}[,\]])");
}
private static void showMatch(string text, string expr) {
MatchCollection mc = Regex.Matches(text, expr);
string[] matches=new string[10000];
foreach (Match m in mc) {
string tailored=m.Value.Trim().Replace("{","");
matches = Regex.Split(tailored, ",");
for(int i=0;i<matches.Length;i++)
{
Console.WriteLine(matches[i].ToString().Trim());
}
}
}
}
输出:
buyerfirstname:Randy
buyermiddlename:null
buyerlastname:Johnson
buyerfullname:Randy Johnson
businessname:null
我希望这可以帮助您解决问题或至少为您提供一个开始的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.