我有以下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; }
}
在JSON中,workspace
包含所有其他内容,因此您应该有如下内容:
class Container {
public Workspace workspace { get; set; }
}
class Workspace {
public string name { get; set; }
public string dataStores { get; set; }
public string coverageStores { get; set; }
public string wmsStores { get; set; }
}
至少匹配JSON的结构-它是否工作是另一回事:)
如果您查看JSON对象(如果您更清楚地布局{
和}
可能会更好),您将看到它试图将所有数据序列化到workspace
字段,而不是其他属性。我希望你的对象看起来更像:
{
"workspace": "whatever",
"name":"Dallas",
"dataStores":"http://.....:8080/geoserver/rest/workspaces/Dallas/datastores.json",
"coverageStores":"http://.....:8080/geoserver/rest/workspaces/Madrid/coveragestores.json",
"wmsStores":"http://....:8080/geoserver/rest/workspaces/Madrid/wmsstores.json"
}