简体   繁体   English

将 json 转换为 List<> C#

[英]Convert json to List<> c#

How to convert Json array to list<> c#如何将Json数组转换为列表<> C#

[[{
    "QID": 1,
    "Question": "Question",
    "IsMultipel": 0
},
{
    "QID": 2,
    "Question": "Question",
    "IsMultipel": 1
}],
[{
    "QID": 1,
    "A_ID": 1,
    "Answer": "Answer"
},
{
    "QID": 1,
    "A_ID": 2,
    "Answer": "Answer"
},
{
    "QID": 1,
    "A_ID": 3,
    "Answer": "Answer"
},
{
    "QID": 1,
    "A_ID": 3,
    "Answer": "Answer"
}]]

Error:To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that I am doing like:错误:要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或我正在执行的类型:

List<QuestionAndAnswerNewMarge> _QuestionAndAnswerNewMarge = new List<QuestionAndAnswerNewMarge>();
string str="[[{\"QID\":1,\"Question\":\"Question\",\"IsMultipel\":0},{\"QID\":2,\"Question\":\"Question\",\"IsMultipel\":1}],[{\"QID\":1,\"A_ID\":1,\"Answer\":\"Answer\"},{\"QID\":1,\"A_ID\":2,\"Answer\":\"Answer\"},{\"QID\":1,\"A_ID\":3,\"Answer\":\"Answer\"},{\"QID\":1,\"A_ID\":3,\"Answer\":\"Answer\"}]]";
_QuestionAndAnswerNewMarge = JsonConvert.DeserializeObject<List<QuestionAndAnswerNewMarge>>(str).ToList();

public class QuestionAndAnswerNewMarge
{
    public List<QuestionNew> QuestionNew { get; set; }
    public List<AnswerNew> AnswerNew { get; set; }

}
public class QuestionNew
{

    public string QuestionID { get; set; }
    public string Question { get; set; }
    public string IsMultiple { get; set; }
}
public class AnswerNew
{

    public string QuestionID { get; set; }
    public string AnswerID { get; set; }
    public string Answer { get; set; }
}

The JSON doesn't really line up to the types your trying to use. JSON 并不真正符合您尝试使用的类型。 You have two options here and the one to take depends on if you can change the JSON string at all.您在此处有两个选项,要选择的选项取决于您是否可以更改 JSON 字符串。

If you can, I suggest just manually building up the objects then serializing them.如果可以,我建议您手动构建对象,然后将它们序列化。 This outputs the Json in the correct form for use and you can setup whoever is generating it to use that format instead.这会以正确的形式输出 Json 以供使用,您可以设置生成它的人使用该格式。

As an example, I tweaked your objects a bit, created an instance of it, recreated your data, then serialized it:例如,我稍微调整了您的对象,创建了它的一个实例,重新创建了您的数据,然后对其进行了序列化:

public class QuestionAndAnswerNewMarge
{
    public List<Question> Questions { get; set; }
    public List<Answer> Answers { get; set; }
}

public class Question
{
    public int QuestionID { get; set; }
    public string QuestionText { get; set; }
    public bool IsMultiple { get; set; }
}
public class Answer
{
    public int QuestionID { get; set; }
    public int AnswerID { get; set; }
    public string AnswerText { get; set; }
}

JSON: JSON:

{
  "Questions": [
    {
      "QuestionID": 1,
      "QuestionText": "Question",
      "IsMultiple": false
    },
    {
      "QuestionID": 2,
      "QuestionText": "Question",
      "IsMultiple": true
    }
  ],
  "Answers": [
    {
      "QuestionID": 1,
      "AnswerID": 1,
      "AnswerText": "Answer"
    },
    {
      "QuestionID": 1,
      "AnswerID": 2,
      "AnswerText": "Answer"
    },
    {
      "QuestionID": 1,
      "AnswerID": 3,
      "AnswerText": "Answer"
    },
    {
      "QuestionID": 2,
      "AnswerID": 1,
      "AnswerText": "Answer"
    }
  ]
}

If you are reading the JSON from an external source, then use a utility like json2csharp to generate classes that will de-serialize using the given json example.如果您从外部源读取 JSON,则使用json2csharp 之类的实用程序生成将使用给定 json 示例进行反序列化的类。

This solution is a little dirty but should work with the JSON string you posted这个解决方案有点脏,但应该适用于您发布的 JSON 字符串

    public void Convert()
    {
        var questionsAnswers = new QuestionsAnswers()
        {
            Answers = new List<Answ>(),
            Questions = new List<Qst>()
        };


        string str = "[[{\"QID\":1,\"Question\":\"Question\",\"IsMultipel\":0},{\"QID\":2,\"Question\":\"Question\",\"IsMultipel\":1}],[{\"QID\":1,\"A_ID\":1,\"Answer\":\"Answer\"},{\"QID\":1,\"A_ID\":2,\"Answer\":\"Answer\"},{\"QID\":1,\"A_ID\":3,\"Answer\":\"Answer\"},{\"QID\":1,\"A_ID\":3,\"Answer\":\"Answer\"}]]";
        var d = JsonConvert.DeserializeObject<dynamic[][]>(str);
        foreach (var objects in d)
        {
            if (objects.All(a => a["A_ID"] == null))
            {
                questionsAnswers.Questions.AddRange(objects.Select(a => new Qst()
                {
                    IsMultipel = a[nameof(Qst.IsMultipel)],
                    Question = a[nameof(Qst.Question)],
                    QID = a[nameof(Qst.QID)]
                }));
            }
            else
            {
                questionsAnswers.Answers.AddRange(objects.Select(a => new Answ()
                {
                    A_ID = a[nameof(Answ.A_ID)],
                    Answer = a[nameof(Answ.Answer)],
                    QID = a[nameof(Answ.QID)]
                }));
            }
        }
    }

    public class QuestionsAnswers
    {
        public List<Qst> Questions { get; set; }
        public List<Answ> Answers { get; set; }
    }

    public class Qst
    {
        public int QID { get; set; }
        public string Question { get; set; }
        public bool IsMultipel { get; set; }
    }

    public class Answ
    {
        public int QID { get; set; }
        public int A_ID { get; set; }
        public string Answer { get; set; }
    }

You could use this.你可以用这个。 Note that you'll need to update your property names and types in the classes:请注意,您需要更新类中的属性名称和类型:

    private void Test()
    {
       QuestionAndAnswerNewMarge q = new QuestionAndAnswerNewMarge();

        JArray ja = JArray.Parse(json);

        var ja1 = JArray.Parse(ja[0].ToString());
        var ja2 = JArray.Parse(ja[1].ToString()); 

        q.QuestionNew = JsonConvert.DeserializeObject<List<QuestionNew>>(ja1.ToString());
        q.AnswerNew = JsonConvert.DeserializeObject<List<AnswerNew>>(ja2.ToString());
    }

    public class QuestionAndAnswerNewMarge
    {
        public List<QuestionNew> QuestionNew { get; set; }
        public List<AnswerNew> AnswerNew { get; set; }
    }
    public class QuestionNew
    {
        public int QID { get; set; }
        public string Question { get; set; }
        public int IsMultiple { get; set; }
    }
    public class AnswerNew
    {
        public string QID { get; set; }
        public string A_ID { get; set; }
        public string Answer { get; set; }
    }

如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C#

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将json转换为列表c# - how to convert json to list c# 将json转换为c#对象列表 - convert json to c# list of objects 在C#中将层级字符串列表转换为JSON - Convert a list of hierachical strings to JSON in C# 如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C# 将 json(具有多个级别)转换为列表 c# - Convert a json (with many levels) into a List c# 如何在 C# 中将列表转换为 JSON? - How to convert a list to JSON in C#? 如何在C#中将JSON响应转换为列表? - How to convert JSON Response to a List in C#? 在C#中将列表转换为json格式 - convert list to json format in c# 如何将JSON数组转换为C#列表? - How to convert a JSON array into a C# List? 将 Json 字符串转换为 C# Object 列表 - Convert Json String to C# Object List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM