我从列表中序列化了一个现有的json,如下所示
var products= JsonConvert.SerializeObject(produstList, Formatting.Indented);
{
"Products": [
{
"Name": "Sample Product",
"Id": "LT2134",
"ProcudtCode": "001KP"
}
]
}
想要将另一个序列化的json对象(ProductList)安装到上面的上面,如下所示,有没有办法实现这一点。
{
"Products": [
{
"Name": "Sample Product",
"Id": "LT2134",
"ProcudtCode": "001KP"
}
],
"ProductList": [
{
"Category": "Electronics",
"SubCategory": "Router",
"ProcudtCode": "001KP",
"Description": "wifi router",
"Brand": "test"
}
]
}
请帮帮我
答案 0 :(得分:1)
您有两个选项,您可以在执行序列化之前附加两个对象,也可以在之后混合两个JSON字符串(这实际上取决于场景)。我建议您为此创建另一个数据模型,否则在反序列化时可能会遇到问题。
我推荐的解决方案是:
public class MixedProduct {
public List<Products> Products {get; set;}
public List<ProductList> ProductList {get; set;}
}
var products= JsonConvert.SerializeObject(new MixedProduct { Products = A, ProductList = B}, Formatting.Indented);
如果由于某些原因您不能或不想这样做,您可以执行以下操作:
var products= JsonConvert.SerializeObject(new Object { Products = A, ProductList = B}, Formatting.Indented);
如果你想附加两个JSON字符串,你可以执行以下操作:
String firstJson = " { \"Products\": [ {} ] } ";
String secondJson = " { \"ProductList\": [ {} ] } ";
var tempFirst = firstJson.TrimStart().TrimEnd();
var tempSecond = secondJson.TrimStart().TrimEnd();
String mixedJson = "{" + tempFirst.Substring(1, tempFirst.Length - 2)
+ "," + tempSecond.Substring(1, tempSecond.Length - 2) + "}";
以下方式混合它们会更安全,以便处理格式稍微错误的JSON字符串:
String mixedJason = "{" + tempFirst.Substring(1, tempFirst.Length - 2).TrimEnd().TrimEnd(',')
+ "," + tempSecond.Substring(1, tempSecond.Length - 2) + "}";