【发布时间】:2016-12-20 15:02:57
【问题描述】:
我在 C# 方面不是最好的,因为我目前仍在学习!但是,我一直无法从资产文件中分配解析的 JSON 值。
解析工作正常,我可以找到路径。但是,该值是作为对象检索的,我无法将其转换为当前 JSON 值的整数。
我将如何以正确的格式检索 JSON 值?可以是字符串或整数。
我已经尝试过Convert.ToInt32(reader.Value) 和(int) reader.Value,如下所示。
但我收到错误Cannot implicitly convert type 'string' to 'int'
另外,我试过JsonConvert.DeserializeObject<T>(reader.Value)
这给出了两个错误:
The type or namespace name 'T' could not be foundArgument 1: cannot convert from 'object to 'string'
注意: CustomerVolumes() 只是一个完整 JSON 响应的 getter/setter 映射类。一些值是字符串或整数。没什么特别的!
使用: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader.htm
也使用:http://json2csharp.com 创建 CustomerVolumes 类
public class DashboardActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Dashboard);
string jsonResponse = ReadFile();
var CustomerVolumes = new CustomerVolumes();
JsonTextReader reader = new JsonTextReader(new StringReader(@jsonResponse));
while (reader.Read())
{
if (reader.Value != null)
{
if (reader.Path.Equals("customers.id.cycles.yyyy_mm.scopes.mms.volume") && !reader.Value.Equals("volume"))
{
CustomerVolumes.customers.id.cycles.yyyy_mm.scopes.mms.volume = Convert.ToInt32(reader.Value);
}
if (reader.Path.Equals("customers.id.cycles.yyyy_mm.scopes.gprs.volume") && !reader.Value.Equals("volume"))
{
CustomerVolumes.customers.id.cycles.yyyy_mm.scopes.gprs.volume = (int) reader.Value;
}
}
}
private string ReadFile()
{
StreamReader sr = new StreamReader(Android.App.Application.Context.Assets.Open(JSON_FILE));
string text = sr.ReadToEnd();
sr.Close();
return text;
}
}
public class Mms
{
public int volume { get; set; }
}
public class Gprs
{
public int volume { get; set; }
}
public class Voice
{
public int volume { get; set; }
}
public class Sms
{
public int volume { get; set; }
}
public class Scopes
{
public Mms mms { get; set; }
public Gprs gprs { get; set; }
public Voice voice { get; set; }
public Sms sms { get; set; }
}
public class YyyyMm
{
public Scopes scopes { get; set; }
}
public class Cycles
{
public YyyyMm yyyy_mm { get; set; }
}
public class Id
{
public Cycles cycles { get; set; }
}
public class Customers
{
public Id id { get; set; }
}
public class CustomerVolumes
{
public Customers customers { get; set; }
}
【问题讨论】:
-
你试过了吗:Int32.Parse(
)? -
是的。但我收到(局部变量)JsonTextReader 阅读器 - 参数 1:无法从“对象”转换为“字符串”
-
通过debug查看
Reader.Value的值是多少? -
JsonConvert.DeserializeObject<T>( string )不能读取指定类的全文吗? -
<T>旨在成为类型。可以反序列化为的类或字符串等标准类型。这类似于您键入List<string>而不是List<T>