如何用JObject创建含对象数组的JSON对象?(Cosmos DB场景)
解决Cosmos DB种子器中JObject数组赋值报错问题
问题原因
你遇到的「Object serialized to Array. JObject instance expected.」报错,核心原因很明确:你的Config属性类型是JObject(对应JSON的对象结构{}),但直接把List<Question>传给JObject.FromObject()时,它会被序列化为JSON数组[],两者类型不匹配,自然触发错误。你需要的是一个包含questions数组的对象,所以得把数组包装在对象容器里再转换。
正确实现语法
错误写法(触发报错)
// 直接传入List<Question>会被序列化为数组,不符合JObject的类型要求 Config = JObject.FromObject(questionList);
正确写法
把List<Question>包装在一个带questions属性的匿名对象中,再转为JObject,就能生成你期望的JSON结构:
// 先构造Question列表 var questionList = new List<Question> { new Question { Key = "contact", Label = "Contact Person", HelpText = "Contact Person", Config = new JObject(), Type = QuestionKind.Textbox, ContextTarget = "$.data.contact", EnabledRule = null, ValidationRules = new List<ValidationRule>(), VisibleRule = null }, new Question { Key = "company", Label = "Company Name", HelpText = "Company Name", Config = new JObject(), Type = QuestionKind.Textbox, ContextTarget = "$.data.company", EnabledRule = null, ValidationRules = new List<ValidationRule>(), VisibleRule = null } }; // 将列表包装在匿名对象中,再转为JObject Config = JObject.FromObject(new { questions = questionList });
这段代码最终生成的JSON结构完全符合你的需求:
"config": { "questions": [ { "key": "contact", "label": "Contact Person", "helpText": "Contact Person", "config": {}, "type": "Textbox", "contextTarget": "$.data.contact", "enabledRule": null, "validationRules": [], "visibleRule": null }, { "key": "company", "label": "Company Name", "helpText": "Company Name", "config": {}, "type": "Textbox", "contextTarget": "$.data.company", "enabledRule": null, "validationRules": [], "visibleRule": null } ] }
额外小提示
如果你的Question类中C#属性名和JSON键名不一致(比如C#的Key对应JSON的key),可以给属性加上[JsonProperty("key")]特性,确保序列化的键名完全匹配预期。
内容的提问来源于stack exchange,提问作者333Matt
相关产品推荐
相关产品推荐

