Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 转换列表<;MyClass>;复制JSON失败_C#_List_Serialization_Json.net - Fatal编程技术网

C# 转换列表<;MyClass>;复制JSON失败

C# 转换列表<;MyClass>;复制JSON失败,c#,list,serialization,json.net,C#,List,Serialization,Json.net,我试图将我的对象列表转换为JSON数组(包装在JSON对象中),但不断出现一个错误,我不知道是什么导致的 列表中对象的我的类: public class BriefResponseTestingDto { public Guid GrantId { get; set; } public string GrantName { get; set; } } 将列表序列化为JSON的代码: List<BriefResponseTestingDto> list = new L

我试图将我的对象列表转换为JSON数组(包装在JSON对象中),但不断出现一个错误,我不知道是什么导致的

列表中对象的我的类:

public class BriefResponseTestingDto
{
    public Guid GrantId { get; set; }
    public string GrantName { get; set; }
}
将列表序列化为JSON的代码:

List<BriefResponseTestingDto> list = new List<BriefResponseTestingDto>();
list.Add(new BriefResponseTestingDto() { GrantId = new Guid(), GrantName = "Name1"});
list.Add(new BriefResponseTestingDto() { GrantId = new Guid(), GrantName = "Name2"});
list.Add(new BriefResponseTestingDto() { GrantId = new Guid(), GrantName = "Name3"});

dataAsJobject = new JObject(JsonConvert.SerializeObject(list));
List List=新列表();
添加(new-BriefResponseTestingDto(){GrantId=new-Guid(),GrantName=“Name1”});
添加(new-BriefResponseTestingDto(){GrantId=new-Guid(),GrantName=“Name2”});
添加(new-BriefResponseTestingDto(){GrantId=new-Guid(),GrantName=“Name3”});
dataAsJobject=newJobject(JsonConvert.SerializeObject(list));
序列化后,我尝试将字符串转换为JObject,并引发异常,消息如下: 无法将Newtonsoft.Json.Linq.JValue添加到Newtonsoft.Json.Linq.JObject。


我做错了什么?

当您要序列化为字符串时,请执行以下操作:

var jsonString = JsonConvert.SerializeObject(list);
要转换回,请执行以下操作:

var myList = JsonConvert.DeserializeObject<List<BriefResponseTestingDto>>(jsonString);

基于我对OP的转换,用户希望能够向现有对象添加数组。有两种方法可以做到这一点,但我倾向于回到
动态
路线

假设我们有一个如下所示的对象:

{
    "hello":"world"
}
{
    "hello":"world",
    "myArray":[1,2,3,4,5]
}
我们想在属性
hello
中添加一个数组作为同级数组,因此它看起来像这样:

{
    "hello":"world"
}
{
    "hello":"world",
    "myArray":[1,2,3,4,5]
}
我们可以通过获取原始模型并将其转换为
dynamic
来实现这一点。由于我们与Newtonsoft紧密耦合,因此我将利用这一优势,让该库完成繁重的工作

下面是一种将对象转换为
ExpandoObject
type
dynamic
的方法,它允许您完成一些非常简洁的事情:

public static dynamic ConvertObjectToExpandoObject(object obj)
{
    using (var ms = new MemoryStream())
    {
        using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, leaveOpen: true))
        using (var jtw = new JsonTextWriter(sw))
        {
            new JsonSerializer().Serialize(jtw, obj);
        }
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        using (var jtr = new JsonTextReader(sr))
        {
            return JsonSerializer.CreateDefault(new JsonSerializerSettings
            {
                Converters = { new ExpandoObjectConverter() }
            }).Deserialize<ExpandoObject>(jtr);
        }
    }
}

您可以在这里使用任何您想要的模型,甚至是具体的模型(不仅仅是匿名对象)。我们向它添加了一个数组,然后将其序列化回来。现在它看起来就像我们想要的上面的结果。

您不能将
JValue
JArray
或另一个
JObject
直接放入
JObject
;您需要将其放入一个
JProperty
(有名称)中,并将其添加到
JObject
。这就是为什么你会看到错误。此外,在将列表添加到
JProperty
之前,应该使用
JArray.FromObject
将列表转换为
JArray
。如果您使用
SerializeObject()
,您将得到一个字符串值,这不是您想要的。有关这方面的更多解释,请参阅

所以你会:

var dataAsJobject = new JObject(new JProperty("data", JArray.FromObject(list)));
var json = dataAsJobject.ToString();
小提琴:

您也可以使用匿名对象获得所需的输出:

var anon = new { data = list };
var json = JsonConvert.SerializeObject(anon, Formatting.Indented);

Fiddle:

只需使用
JsonConvert.SerializeObject
。这将返回一个json字符串,您不需要将其放入
JObject
@John,Newtonsoft的json.NET似乎没有JObject.From()方法。我打赌您甚至不需要将其转换为JObject
JsonConvert.DeserializeObject(jsonString)引发异常“无法将类型为“Newtonsoft.Json.Linq.JArray”的对象强制转换为类型为“Newtonsoft.Json.Linq.JObject”。@Val--抱歉,忘记了我们正在使用
列表
JObject
是一个对象,而不是数组。您需要使用
JArray
。将更新我的答案。为什么你只需要
J-Anything
?您想完成什么?我想将数组插入JSON对象中的属性:
{“data”:[item1,item2,item3]}
@Val——更新的答案向您展示了如何向现有对象添加属性。