【发布时间】:2014-11-07 07:20:50
【问题描述】:
我有 json 字符串作为
{"AccountNo":"345234533466","AuthValue":"{\"TopUpMobileNumber\":\"345234533466\",\"VoucherAmount\":\"100\"}"}
为了解析这个字符串,我创建了一个类
public class UserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
}
在 AuthValue 中,它给我的输出为{\"TopUpMobileNumber\":\"345234533466\",\"VoucherAmount\":\"100\"},这是绝对正确的。现在我想修改我的类,我希望AuthValue 也采用字符串格式和单独的成员变量格式。
所以我以这种方式修改了我的课程,但它给出了错误
public class UserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
public Auth ????? { get; set; }
}
public class Auth
{
public string TopUpMobileNumber { get; set; }
public string VoucherAmount { get; set; }
}
我的要求是
- 我需要 AuthValue 整个 json 字符串
- 在另一个变量中我想要成员明智的值
解析逻辑
UserContext conObj1 = new UserContext();
conObj1 = JsonConvert.DeserializeObject<UserContext>(context);
注意:不允许修改 json 字符串。
【问题讨论】:
-
嗯,是的,它会给你一个错误 - 一方面是因为你试图声明两个具有相同名称的成员。但它很容易修复,至少使用 JSON.NET。 (不幸的是,我现在没有时间发布答案......)
-
事情是,如果我修改我的变量名,我将无法解析
json字符串 -
您尝试使用单个类来表示两种不同的事物——一种是字符串,另一种是对象。我们不知道您使用什么进行 JSON 解析,这无济于事。
-
@JonSkeet 我正在使用
JsonConvert -
顺便说一句,使用
SomeType x = new SomeType(); x = someExpression;几乎总是毫无意义的。只需使用SomeType x = someExpression;。为什么要创建不需要的对象?