本文介绍了如何在C#中使用JsonWriter序列化数据组成一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找可以使用C#中的JsonWriter序列化包含数组的数据的东西吗?

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

这是我得到的错误:

ExceptionMessage:不受支持的类型:Module.Model.Acl_Entries [].使用JsonSerializer类获取对象的JSON表示形式.路径'acl_entries'."ExceptionType:"Newtonsoft.Json.JsonWriterException"

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"

这是我的数据:

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

这是我的控制器:

 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);

    }

这是我的JsonWriter:

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;
    }

所以我的问题是,我该如何在C#中使用JsonWriter序列化包含数组的数据,或者有人可以给我提示.

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.

推荐答案

writer.WriteStartArray()writer.WriteStartArray()的要求是像[1,2,3,4,5]['a','b','c]这样的简单对象,即是integer类型的数组或string.但是您要输入的是object-array:

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"            
 }]

JsonWriter无法获得其类型.因此,您有两个选择:

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

  1. 将数组对象转换为json字符串,然后将其放入对象acl_entries(即正在对其进行序列化的)中,如下所示:

  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);

注意:您也可以使用Newtonsoft.json.

  1. 或者如如何使用 OP 是:

启动数组对象- >遍历所有条目以创建每个条目的对象,然后结束数组对象.

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.

这篇关于如何在C#中使用JsonWriter序列化数据组成一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!