gpt4 book ai didi

C# - 从 JSON 反序列化,结果始终是一个空对象

转载 作者:行者123 更新时间:2023-11-30 12:55:17 27 4
gpt4 key购买 nike

我尝试从 JSON 字符串中读取 c# 中的对象 - 但结果始终是一个空对象,没有任何异常 - 但我没有看到错误

我从网络服务获取的 JSON 字符串是

{  
"CustomUserFields":{
},
"CustomApplicationFields":{
},
"Attachments":[
],
"Tags":[
],
"HasModifyEntriesAccess":true,
"HasViewEntryContentsAccess":true,
"CommentPrompts":{
"AskForCommentOnViewPassword":false,
"AskForCommentOnViewOffline":false,
"AskForCommentOnModifyEntries":false,
"AskForCommentOnMoveEntries":false,
"AskForCommentOnMoveFolders":false,
"AskForCommentOnModifyFolders":false
},
"Id":"c51ca807-9e01-4652-95d0-645a0914b1ba",
"Name":"SecondOne",
"Username":"Second@test.domain",
"Password":null,
"Url":"",
"Notes":"Bla Bla Bla",
"GroupId":"1182570d-d22d-4f2a-babb-3dab4ff48852",
"Created":"2018-02-27T14:39:15+01:00",
"Modified":"2018-02-27T14:39:15+01:00",
"Expires":null,
"UsageComment":null
}

我的代码是这样的

DataContractJsonSerializer serF = new DataContractJsonSerializer(typeof(Credential));
Credential cred1 = new Credential();
MemoryStream msF = new MemoryStream(Encoding.UTF8.GetBytes(response2.Content));
cred1 = serF.ReadObject(msF) as Credential;
msF.Close();

[Serializable, XmlRoot("Credential"), DataContract(Name = "Credential")]
public class Credential
{
[DataMember]
public Guid id = Guid.Empty;
[DataMember]
public Guid groupid = Guid.Empty;
[DataMember]
public string name = String.Empty;
}

我从类中删除了一些属性以简化代码阅读 - 但这没有什么区别

Credential 对象 cred1 的属性始终为空

最佳答案

来自您的 Json 的 C# 类(通过以下方式自动生成:http://json2csharp.com/):

public class CustomUserFields
{
}

public class CustomApplicationFields
{
}

public class CommentPrompts
{
public bool AskForCommentOnViewPassword { get; set; }
public bool AskForCommentOnViewOffline { get; set; }
public bool AskForCommentOnModifyEntries { get; set; }
public bool AskForCommentOnMoveEntries { get; set; }
public bool AskForCommentOnMoveFolders { get; set; }
public bool AskForCommentOnModifyFolders { get; set; }
}

public class RootObject
{
public CustomUserFields CustomUserFields { get; set; }
public CustomApplicationFields CustomApplicationFields { get; set; }
public List<object> Attachments { get; set; }
public List<object> Tags { get; set; }
public bool HasModifyEntriesAccess { get; set; }
public bool HasViewEntryContentsAccess { get; set; }
public CommentPrompts CommentPrompts { get; set; }
public string Id { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public object Password { get; set; }
public string Url { get; set; }
public string Notes { get; set; }
public string GroupId { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public object Expires { get; set; }
public object UsageComment { get; set; }
}

注意区分大小写

关于C# - 从 JSON 反序列化,结果始终是一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50562128/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com