Sending Json with nested array of JTokens to remote server – C#

huangapple go评论72阅读模式
英文:

Sending Json with nested array of JTokens to remote server - C#

问题

I can help you with the translation. Here's the translated text you requested:

我正在尝试将一个JSON对象发送到远程的第三方Web API URL。我正在使用C#构建这个对象。

生成的序列化JSON对象如下所示:

{
    "ID": 1,
    "TypeID": 1,
    "UserName": "tempUser",
    "Attributes": [{
        "ID": 13023,
        "Value": "Nonemp Status"
    }, {
        "ID": 13022,
        "Value": "Research Status"
    }, {
        "ID": 13021,
        "Value": "ACT"
    }, {
        "ID": 13024,
        "Value": "Temp Status"
    }, {
        "ID": 13025,
        "Value": "Temp"
    }]
}

问题出在"attributes"项上。它应该是一个嵌套的JArray。不幸的是,这个发送方法将JArray转换为字符串,导致上传失败。当我重新编写对象以使其成为JArray时,一切都通过。

工作中
{
    "ID": 1,
    "TypeID": 1,
    "UserName": "tempUser",
    "Attributes": [{
        "ID": 13023,
        "Value": "Nonemp Status"
    }, {
        "ID": 13022,
        "Value": "Research Status"
    }, {
        "ID": 13021,
        "Value": "ACT"
    }, {
        "ID": 13024,
        "Value": "Temp Status"
    }, {
        "ID": 13025,
        "Value": "Temp"
    }]
}

嵌套的"Attributes" JArray可以包含从2个项到20个项不等。是否有人知道如何序列化或从传递给C#.NET对象的方式创建JSON对象,使其类似于"working" JSON版本?

英文:

I'm trying to send a json object to a remote 3rd party Web api url. I am building this object using c#

private string SendWebRequest(string url, string requestMethod, string bearer = null, object temp_obj_body = null)
{
    string result = null;
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = requestMethod.ToUpper();

    // Sets the Security Token
    if (bearer != null)
    {
        httpWebRequest.Headers.Add("Authorization", "Bearer " + bearer);
    }

    //Writes to the request service if body is present
    if (temp_obj_body != null)
    {
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.CheckAdditionalContent = true;
            settings.Formatting = Formatting.Indented;
            settings.MetadataPropertyHandling = MetadataPropertyHandling.Default;
            settings.NullValueHandling = NullValueHandling.Include;
            settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
            settings.StringEscapeHandling = StringEscapeHandling.Default;
            settings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
            settings.TypeNameHandling = TypeNameHandling.All;
            settings.MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead;

            var json = JsonConvert.SerializeObject(temp_obj_body, settings);
            streamWriter.Write(json);
        }
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    //Reads the response and gets the response.
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }
    return result;

the serialized JSON object that is generated looks like this

{
    "ID": 1,
    "TypeID": 1,
    "UserName": "tempUser",
    "Attributes": "[{\"ID\":13023,\"Value\":\"Nonemp Status\"},
{\"ID\":13022,\"Value\":\"Research Status\"},
{\"ID\":13021,\"Value\":\"ACT\"},
{\"ID\":13024,\"Value\":\"Temp Status\"},
{\"ID\":13025,\"Value\":\"Temp\"}]"
}

The issue with this is with the "attributes" item. This is supposed to be a nested JArray. Unfortunately, this send method converts the JArray into a string and caused the upload to fail. When I re-write the object to be a JArray, everything passes.

Working
{
    "ID": 1,
    "TypeID": 1,
    "UserName": "tempUser",
    "Attributes": [{"ID":13023,"Value":"Nonemp Status"},
{"ID":13022,"Value":"Research Status"},
{"ID":13021,"Value":"ACT"},
{"ID":13024,"Value":"Temp Status"},
{"ID":13025,"Value":"Temp"}]
}

The nested "Attributes" JArray can be anywhere from 2 items or 20 items. Does anyone know how to serialize or create the JSON object like the "working" JSON version from a passed in c#.NET object?

答案1

得分: 1

您的 Attributes 属性数组值被序列化了两次,所以您也需要进行两次解析。
您可以尝试以下代码:

using Newtonsoft.Json;

result = streamReader.ReadToEnd();

var jObj = JObject.Parse(result);
jObj["Attributes"] = JArray.Parse((string)jObj["Attributes"]);
return jObj.ToString();
英文:

Your Attributes property array value was serialized twice, so you have to parse it twice too.
You can try this code:

using Newtonsoft.Json;

result = streamReader.ReadToEnd();

var jObj = JObject.Parse(result);
jObj["Attributes"] = JArray.Parse((string)jObj["Attributes"]);
return jObj.ToString();

huangapple
  • 本文由 发表于 2023年6月8日 03:19:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定