我有以下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”类型。
有什么想法吗?感谢
答案 0 :(得分:7)
您的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; }
}
答案 1 :(得分:3)
在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的结构相匹配 - 无论它是否有效都是另一回事:)
答案 2 :(得分:0)
如果您查看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"
}