howto Serialize data consist an array using JsonWriter in C#

梦想的初衷 提交于 2021-02-05 11:54:47

问题


I'm looking for something that can be Serialize data that consist an Array using JsonWriter in C#?

This is an error that im getting:

ExceptionMessage: "Unsupported type: Module.Model.Acl_Entries[]. Use the JsonSerializer class to get the object's JSON representation. Path 'acl_entries'." ExceptionType: "Newtonsoft.Json.JsonWriterException"

This is my Data:

"author": {        
            "stakeholder_id": "stkh-a23ee7909d024a21a54fb60d60089c97",
            "username": "alex",
            "acl_entries": [{
                "stakeholder_id": "stkh-f8e80f32aad44df6a7a96b20d4fee340",
                "stakeholder_name": "james",
                "stakeholder_type_id": "5"            
            }]
        }
    }

This is my Controller:

 public class AuthorRequest
    {
        public Stakeholder author { get; set; }

    }

    [HttpPut]
    [ActionName("PutUpdateStakeholder")]
    public string PutUpdateStakeholder(AuthorRequest request)
    {                              
        var author = request.author;

        List <Stakeholder> list = _repos.PutUpdateStakeholder(author);


        //Utils.Log("stakeBasic" + author );

        return JsonConvert.SerializeObject(list);

    }

This is my JsonWriter:

 public List<Stakeholder> PutUpdateStakeholder(Stakeholder author)
    {

        Utils.Log("Update>>>" + author);

        string sMsg = "";

        StringWriter sw = new StringWriter();

        using (JsonWriter writer = new JsonTextWriter(sw))
        {
            writer.Formatting = Formatting.None;

            writer.WriteStartObject();

            object obj = null;

            object fal = false;

            object tr = true;

            object val = 0;               

            writer.WritePropertyName("stakeholder_id");
            writer.WriteValue(author.stakeholder_id);

            writer.WritePropertyName("username");
            writer.WriteValue(author.username);


            writer.WritePropertyName("acl_entries");                        //array

            writer.WriteStartArray();
            //writer.WriteStartObject();

            writer.WriteValue(author.acl_entries);


            //writer.WriteEndObject();
            writer.WriteEnd();               

            writer.WriteEndObject();

        }

         string sParam = "param=" + sw.ToString();

        string sResp = "";

        Utils.Log("BASIC" + sParam);

        List<Stakeholder> list = new List<Stakeholder>();

        if (Utils.GenerateRequest("Stakeholder", sParam, "PUT", ref sResp))
        {
            Utils.deserializeStakeholderResp(sResp, ref list, ref sMsg);

            //Utils.Log("BASIC" + sParam);
        }
        else
        {
            sMsg += sResp;
        }

        return list;
    }

So my question is, how can i Serialize Data that consist an Array using JsonWriter in C# or maybe someone could give me a hint on this.


回答1:


What the JsonWriter require for a writer.WriteStartArray() is a simple object like [1,2,3,4,5] or ['a','b','c] i.e. is an array of type integer or string. But what you are feeding in it is an object-array:

"acl_entries": [{
            "stakeholder_id": "stkh-f8e80f32aad44df6a7a96b20d4fee340",
            "stakeholder_name": "james",
            "stakeholder_type_id": "5"            
 }]

Which the JsonWriter is not able to get the type of. So, you have two options:

  1. Convert the array object into a json string and put it in the object acl_entries (i.e.that is serialize it) as:

    JavaScriptSerializer serializera = new JavaScriptSerializer();
    string res = serializera.Serialize(author.acl_entries);
    jsonWriter.WriteValue(res);
    

Note: you can also use Newtonsoft.json for it.

  1. Or as it is explained in the How to serialize nested collection using JsonWriter by OP is:

    start an array object - > loop through all the entries to create an object of each entry and then end the array-object.

you can change your code to something like this:

writer.WritePropertyName("acl_entries");
jsonWriter.WriteStartArray();

for (int row = 0; row <= author.acl_entries.Count; row++)
{        
    jsonWriter.WriteStartObject();  

    jsonWriter.WritePropertyName("stakeholder_id");
    jsonWriter.WriteValue(author.acl_entries[row].stakeholder_id);

    jsonWriter.WritePropertyName("stakeholder_name");
    jsonWriter.WriteValue(author.acl_entries[row].stakeholder_name);

    jsonWriter.WritePropertyName("stakeholder_type_id");
    jsonWriter.WriteValue(author.acl_entries[row].stakeholder_type_id);
    jsonWriter.WriteEndObject();

}

jsonWriter.WriteEndArray();

Note: You can modify the above logic to have a dynamic implementation where you don't have to hardcode the fields and their value getters.



来源:https://stackoverflow.com/questions/52417556/howto-serialize-data-consist-an-array-using-jsonwriter-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!