我已经看过其他类似的问题,但无法为我的特殊情况找到答案。
我正在创建一个json文件,该文件将由另一个程序解析(不是我的,所以无法重写)。最终产品必须是对象,而不是数组。到目前为止,我只能使用需要包含的数据创建一个JArray。
我创建了一个列出所有json属性的模型。我创建了一个列表来调用模型并为每个属性分配值。
我如何拥有一个包含所有必需信息但不是数组格式的最终json文件?现在,我继续收到错误消息: “对象序列化为预期的数组jobject实例”
public class CreateSummaryModel
{
public CreateSummaryModel(){
CreateAddressModel = new CreateAddressModel();
ProductName = new ProductName();
}
public CreateAddressModel CreateAddressModel { get; set; }
public ProductName ProductName { get; set; }
}
public class CreateAddressModel
{
public string City { get; set; }
}
public class ProductName
{
public string ProductName { get; set; }
}
List<CreateSummaryModel> output = new List<CreateSummaryModel>();
foreach (var product in order.product.name)
output.Add(new CreateSummaryModel()
{ CreateAddressModel =
{ City = order.address.city },
ProductName =
{ ProductNames = order.product.name },
});
string json = JsonConvert.SerializeObject(output);
File.WriteAllText(fullPath, json.ToString());
我尝试过:
JObject jobjectObject = new JObject();
jobjectObject = JObject.FromObject(output);
AND
JArray jobjectArray = new JArray();
jobjectObject = jobjectArray.ToObject<List<CreateSummaryModel>>();
AND
string json = JsonConvert.SerializeObject(jobjectObject);
string jsonD = JsonConvert.DeserializeObject<List<CreateSummaryModel>>(json);
最终产品必须采用以下格式:
{
"address": {
"city": "Rivendell"
},
"productName": [
"productName": "Lembas Bread",
"productName": "Mushrooms"
]
}
答案 0 :(得分:2)
您创建的模型类的结构与“其他程序”所期望的完全不同。
您显示的样本JSON无效。假设您的意思是:
{
"address": {
"city": "Rivendell"
},
"productName": [
"Lembas Bread",
"Mushrooms"
]
}
为此的模型类为:
public class CreateSummaryModel
{
[JsonProperty("address")]
public Address Address { get; set; }
[JsonProperty("productName")]
public List<string> ProductName { get; set; }
}
public class Address
{
[JsonProperty("city")]
public string City { get; set; }
}
您可以像这样填充模型:
var output = new CreateSummaryModel();
output.Address = new Address { City = order.address.city };
// I didn't quite understand what your "order" object contains.
// I assumed it has a bunch of products with names.
output.ProductName = order.products.Select(x => x.name).ToList();
string json = JsonConvert.SerializeObject(output);