在c#中向传递给WCF服务的JSON添加前缀标记

qmelpv7a  于 2022-12-30  发布在  C#
关注(0)|答案(2)|浏览(130)

我们将JSON请求传递给包含一些附加前缀(如xy 1)的WCF服务,xy 2和“@”符号等,使其成为自定义JSON。我们的WCF服务的创建订单方法处理此自定义JSON以创建订单。我们希望将标准JSON传递给WCF服务,而不是自定义JSON。有没有办法把标准的JSON传递给WCF服务,然后用最少的代码修改把它转换回自定义的JSON?
注意:这是示例JSON,但实际的JSON文件很长,包含更多细节。
定制的JSON如下:

{
    "xy1:createOrder": {
        "@test:xy1": "http://www.testing.com/schema/order",
        "@test:xy2": "http://www.testing.com/schema/customer",
        "xy1:order": {
            "@Date": "2022-12-27",
            "@orderNo": "FirstOrder1"
        },
        "xy2:customer": {
            "@Id": "1",
            "xy2:title": "Mr",
            "xy2:fName": "Alex",
            "xy2:lName": "John",
            "xy2:emailId": "aj@gmail.com"
        }
    }
}

标准JSON如下所示:

{
    "createOrder": {
        "order": {
            "Date": "2022-12-27",
            "orderNo": "FirstOrder1"
        },
        "customer": {
            "Id": "1",
            "title": "Mr",
            "fName": "Alex",
            "lName": "John",
            "emailId": "aj@gmail.com"
        }
    }
}
f0brbegy

f0brbegy1#

你可以试试这个代码

var origJObj = JObject.Parse(json).Dump();
    var cleanedJObj = new JObject();
    
    CleanJsonObject(origJObj, cleanedJObj);

    //if you need a json
    json = cleanedJObj.ToString();

public void CleanJsonObject(JObject origJObj, JObject cleanedJObj)
{
    foreach (var prop in origJObj.Properties())
    {
        var name = "";
        var startIndex = prop.Name.IndexOf(":");
        if (startIndex > 0)
        {
            name = prop.Name.Substring(startIndex + 1);
        }
        else name = prop.Name.Replace("@", "");
        if (prop.Value.Type == JTokenType.Object)
        {
            var newJObj = new JObject();
            CleanJsonObject((JObject)prop.Value, newJObj);
            cleanedJObj.Add(name, newJObj);
        }
        else
        {
            cleanedJObj.Add(name, prop.Value);
        }
    }
}
ut6juiuv

ut6juiuv2#

除了删除代码中不必要的部分之外,还可以尝试使用josn.net来自定义您的需求。
如何使用它的示例:

public class User
{
    public User(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject["user"];
        name = (string) jUser["name"];
        teamname = (string) jUser["teamname"];
        email = (string) jUser["email"];
        players = jUser["players"].ToArray();
    }

    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

// Use
private void Run()
{
    string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
    User user = new User(json);

    Console.WriteLine("Name : " + user.name);
    Console.WriteLine("Teamname : " + user.teamname);
    Console.WriteLine("Email : " + user.email);
    Console.WriteLine("Players:");

    foreach (var player in user.players)
        Console.WriteLine(player);
 }

相关问题