C# 将JSON文件导入C对象时遇到问题
我正试图将一个JSON文件导入Mac上C VS 2017中的一个对象,以便对其执行进一步的操作 我有一个JSON文件示例:C# 将JSON文件导入C对象时遇到问题,c#,json,C#,Json,我正试图将一个JSON文件导入Mac上C VS 2017中的一个对象,以便对其执行进一步的操作 我有一个JSON文件示例: { "subdomain": "mycompany", "name": "MyCompany Inc", "website": "https://www.mycompany.com", "edition": "DIRECTORY", "licensing": { "apps": [ "boxnet" ] },
{
"subdomain": "mycompany",
"name": "MyCompany Inc",
"website": "https://www.mycompany.com",
"edition": "DIRECTORY",
"licensing":
{
"apps":
[
"boxnet"
]
},
"admin": {
"profile":
{
"firstName": "John",
"lastName": "Smith",
"email": "joe@mycompany.com",
"login": "joe@mycompany.com",
"mobilePhone": null
},
"credentials":
{
"password":
{
"value": "NotAPassword"},
"recovery_question":
{
"question": "Best Solution",
"answer": "MyOne"
}
}
}
}
}
因此,我生成了一个C库来创建要导入的对象类型:
using System;
namespace OrgCustom
{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Licensing
{
public List<string> apps { get; set; }
}
public class Profile
{
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string login { get; set; }
public object mobilePhone { get; set; }
}
public class Password
{
public string value { get; set; }
}
public class RecoveryQuestion
{
public string question { get; set; }
public string answer { get; set; }
}
public class Credentials
{
public Password password { get; set; }
public RecoveryQuestion recovery_question { get; set; }
}
public class Admin
{
public Profile profile { get; set; }
public Credentials credentials { get; set; }
}
public class Org
{
public string subdomain { get; set; }
public string name { get; set; }
public string website { get; set; }
public string edition { get; set; }
public Licensing licensing { get; set; }
public Admin admin { get; set; }
}
}
所以,我应该能够很容易地导入文件,使用Newtownsoft.Json库
我的程序代码是:
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using RestSharp;
using Newtonsoft.Json;
using OrgCustom;
namespace TestStart
{
class Program
{
static void Main(string[] args)
{
string JSONstring = File.ReadAllText("CreateOrgExample.json");
OrgCustom.Org objOrg = JsonConvert.DeserializeObject<OrgCustom.Org>(JSONstring);
Console.WriteLine(objOrg.ToString());
}
}
}
问题是,当我运行它时,我从反序列化行得到一条消息,JsonConvert是一个类型,在给定上下文中无效
我做错了什么?我在《JSON与C MVA入门》课程中看到了这句话,我相信它应该有用
提前感谢,
QuietLeni乍一看,我没有看到语法错误。您可以检查程序集引用,然后使用global::qualifier和intellisense组合来深入到convert调用,但在我看来它仍然是正确的 另一方面,Password类没有定义JSON片段中的RecoveryQuestion属性
但是,这不应阻止Newtonsoft将JSON片段反序列化到您定义的结构中。JSON结尾处有一个额外的右括号似乎是个问题。所以你可能会在解析时出错。我使用VS2017.net core 2在PC上进行了测试,结果正常。删除最后一个“}”后,谢谢你-我还不够强迫症!我也这么做了!