c# – 反序列化JSON时出错无法将JSON对象反序列化为“System.String”类型

我有以下JSON

{"workspace": {
  "name":"Dallas",
   "dataStores":"http://.....:8080/geoserver/rest/workspaces/Dallas/datastores.json",
   "coverageStores":"http://.....:8080/geoserver/rest/workspaces/Dallas/coveragestores.json",
   "wmsStores":"http://....:8080/geoserver/rest/workspaces/Dallas/wmsstores.json"}}

我试图在这个类中反序列化:

 class objSON {
        public string workspace { get; set; }
        public string name { get; set; }
        public string dataStores { get; set; }
        public string coverageStores { get; set; }
        public string wmsStores { get; set; }}

 objWS_JSON deserContWS = JsonConvert.DeserializeObject<objWS_JSON>(data);
           var coberturas = deserContWS.coverageStores;
           var almacenesDatos = deserContWS.dataStores;
           var almacenesWMS = deserContWS.wmsStores;
           var nombre = deserContWS.name;

我收到以下错误:

无法将JSON对象反序列化为“System.String”类型.

有任何想法吗?谢谢

最佳答案
您的json对于您提供的类结构不正确. json暗示name,dataStores,coverageStores和wmsSTores是工作空间类的子节点.我认为你想要的类结构是这样的:

public class workspace
{
    public string name { get; set; }
    public string dataStores { get; set;}
    public string coverageStores { get; set;}
    public string wmsStores {get; set;}
}

public class objSON
{
    public workspace workspace {get; set;}
}

试试看,如果那个数据结构不是你以后那么你需要改变你的json.

好吧,我刚试过一个示例应用程序,似乎工作正常.这是我使用的代码:

    class Program
    {
            static void Main(string[] args)
            {

               string str = @"{""workspace"": {
                  ""name"":""Dallas"",
                  ""dataStores"":""http://.....:8080/geoserver/rest/workspaces/Dallas/datastores.json"",
                  ""coverageStores"":""http://.....:8080/geoserver/rest/workspaces/Dallas/coveragestores.json      "",
                  ""wmsStores"":""http://....:8080/geoserver/rest/workspaces/Dallas/wmsstores.json""}}";

                 var obj = JsonConvert.DeserializeObject<objSON>(str);

    }

}

public class workspace
{
    public string name { get; set; }
    public string dataStores { get; set; }
    public string coverageStores { get; set; }
    public string wmsStores { get; set; }
}

public class objSON
{
    public workspace workspace { get; set; }
}

转载注明原文:c# – 反序列化JSON时出错无法将JSON对象反序列化为“System.String”类型 - 代码日志