我正在尝试从多级JSON数组中获取对象。这是一个示例表: array(2){
["asd"]=>
array(3) {
["id"]=>
int(777)
["profile"]=>
array(4) {
["username"]=>
string(5) "grega"
["email"]=>
string(18) "random@example.com"
["image"]=>
string(16) "http...image.jpg"
["age"]=>
int(26)
}
["name"]=>
string(5) "Grega"
}
["be"]=>
array(4) {
["username"]=>
string(5) "grega"
["email"]=>
string(18) "random@example.com"
["image"]=>
string(16) "http...image.jpg"
["age"]=>
int(26)
}
}
我想要访问的字符串是其中一封电子邮件(示例)。这是我尝试的方式:
public class getAsd
{
public string asd;
}
public class Profile
{
public string username { get; set; }
public string email { get; set; }
public string image { get; set; }
public string age { get; set; }
}
}
然后使用JavaScriptSerilization.Deserilize<Asd>(jsonData);
对其进行deserilize,但是当我尝试使用“Profile”时,它会给我以下错误:
No parameterless constructor defined for type of 'System.String'.
JSON:
{"asd":{"id":777,"profile":{"username":"grega","email":"random@example.com","image":"http...image.jpg","age":26},"name":"Grega"},"be":{"username":"grega","email":"random@example.com","image":"http...image.jpg","age":26}}
想出可能出现的问题?
答案 0 :(得分:2)
[编辑:Smarm删除。 OP确实在编辑中添加了JSON。]
您的个人资料类(如JSON)应类似于以下内容。
{
"username":"grega",
"email":"random@example.com",
"image":"http...image.jpg",
"age":"26",
"roles": [
{"name": "foo"},
{"name": "bar"}
]
}
array
不应出现在JSON中,除非它属于属性名称("codearray"
)或属性值("There's no 'array' in JSON. There's no 'array' in JSON."
)。
JSON中的对象数组包含在方括号[]
和逗号分隔中。 JSON中的数组/配置文件集合:
[
{
"username":"gretta",
"email":"mrshansel@example.com",
"image":"http...image.jpg",
"age":"37",
"roles": [
{"name": "foo"},
{"name": "bar"}
]
},
{
"username":"methusaleh",
"email":"old@men.org",
"image":"http...image.jpg",
"age":"2600",
"roles": [
{"name": "foo"},
{"name": "},
{"name": "bar"}
]
},
{
"username":"goldilocks",
"email":"porridge@bearshous.com",
"image":"http...image.jpg",
"age":"11",
"roles": [
{"name": "foo"}
]
}
]
虽然这可能无法完全回答您的问题,但您可以从此开始并更新您的问题吗?
编辑: 有关完整方法,请参阅this answer by Hexxagonal。
答案 1 :(得分:1)
好的,这是你的课程的“基本”版本。你应该遵循一个标准,让财产的第一个字母大写。由于你之前没有这样做,我保持了这种风格。
public class Type1
{
public TypeAsd asd { get; set; }
public TypeBe be { get; set; }
}
public class TypeAsd
{
public int id { get; set; }
public TypeBe profile { get; set; }
public string name { get; set; }
}
public class TypeBe
{
public string username { get; set; }
public string email { get; set; }
public string image { get; set; }
public int age { get; set; }
}
您的反序列化代码将如下所示:
string jsonString = "{\"asd\":{\"id\":777,\"profile\":{\"username\":\"grega\",\"email\":\"random@example.com\",\"image\":\"http...image.jpg\",\"age\":26},\"name\":\"Grega\"},\"be\":{\"username\":\"grega\",\"email\":\"random@example.com\",\"image\":\"http...image.jpg\",\"age\":26}}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
Type1 obj = serializer.Deserialize<Type1>(jsonString);