【问题标题】:Cannot implicitly convert type 'string' to 'int'无法将类型“string”隐式转换为“int”
【发布时间】: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 found
  • Argument 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>

标签: c# json xamarin json.net


【解决方案1】:

在您的情况下无需使用 JsonReader,因为您有一个为完整 JsonResponse 生成的对象,名为 CustomerVolumes

要在您的方法中使用它,只需使用:

var customerVolumes = JsonConvert.DeserializeObject<CustomerVolumes>( jsonResponse );

这将为您提供一个 CustomerVolumes 的新实例,其中所有值都已正确填写。

无需解析完整的对象和正确的路径。

例如,您可以查看.netfiddle,它接受一个 json 对象并将其转换为 C# 类。

由于我没有您正在使用的任何数据,这是一个小示例程序来展示它是如何工作的

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;

public class Program
{
    static string fakeJsonString = 
        @"{ ""text"": ""This is a text"", ""intValue"": 10, ""dictionary"": { ""key"": ""value"" }, ""array"": [ 10, 20, 30 ] }";


    internal class FakeObject {
        [JsonProperty("text")]
        public string Text { get;set; }
        [JsonProperty("intValue")]
        public int IntValue { get;set; }
        [JsonProperty("dictionary")]
        public Dictionary<string, string> Dictionary { get;set; }
        [JsonProperty("array")]
        public int[] IntArray { get;set; }
    }

    public static void Main()
    {
        var fakeObject = JsonConvert.DeserializeObject<FakeObject>( fakeJsonString );
        Console.WriteLine("Current value for text: "  + fakeObject.Text);
        Console.WriteLine("Current value for intValue: "  + fakeObject.IntValue);
        Console.WriteLine("Current value for Dictionary: "  + string.Join( ",", fakeObject.Dictionary.Select(kvp => "\"" + kvp.Key + "\": \"" + kvp.Value + "\"" ) ) );
        Console.WriteLine("Current value for IntArray: "  + string.Join( ",", fakeObject.IntArray));
    }
}

【讨论】:

  • 我对此有点困惑!请记住,我不精通 C#。我实现了: var fakeObject = JsonConvert.DeserializeObject(@jsonResponse); Console.WriteLine(fakeObject.customers.id.cycles.yyyy_mm.scopes.gprs.volume);并收到:System.NullReferenceExceipt:对象引用未设置为对象的实例。
  • 另外,id 和 yyyy_mmm 也总是不同的整数值。现在,我正在从资产 json 文件中测试工具。因此,尝试将其与对象类进行匹配和映射并不是 100% 有效
  • @tfont 没问题,请注意我还提到这很难,因为我不知道您的 Json 数据是什么样子或如何实现 CustomerVolumes。如果您可以提供一些示例数据和 CustomerVolumes 的实现,它会变得容易得多。
  • @tfont,请将其添加到您的问题中,在 cmets 中读起来太难了 ;)
  • 将课程添加到我的问题中:]
【解决方案2】:

不熟悉您要做什么,但只是一个值得尝试的猜测。 On this website 它显示 JsonReader.Value 属性返回一个对象而不是字符串。也许尝试显式地执行 reader.value.tostring() 并将其转换为整数。如果类型正确,我看不出您的代码为什么不起作用。

至于JsonConvert.DeserializeObject&lt;T&gt;(reader.Value),请确保您将 T 换成如下字符串:

JsonConvert.DeserializeObject<String>(reader.Value)

祝你好运!

编辑:

不熟悉您要做什么,但只是一个值得尝试的猜测。 On this website 它显示 JsonReader.Value 属性返回一个对象而不是字符串。也许尝试显式地执行 reader.value.tostring() 并将其转换为整数。如果类型正确,我看不出您的代码为什么不起作用。

至于JsonConvert.DeserializeObject&lt;T&gt;(reader.Value),请确保您将 T 换成如下字符串:

JsonConvert.DeserializeObject<String>(reader.Value)

祝你好运!

编辑:

while (reader.Read())
{
    if (reader.Value != null)
    {
        string rVal = (string)reader.Value
        if (reader.Path.Equals("customers.id.cycles.yyyy_mm.scopes.mms.volume") && !(rVal.toUpper() == "VOLUME"))
        {
            CustomerVolumes.customers.id.cycles.yyyy_mm.scopes.mms.volume = Convert.ToInt32(rVal);
        }
}

当你尝试这样做时会发生什么?

【讨论】:

  • 谢谢!仍在玩这个 DeserializeObject,但似乎无处可去!我试过 string str = JsonConvert.DeserializeObject(reader.Value);并收到”参数 1:无法从 'object' 转换为 'string'
  • 我使用了偷偷摸摸的 JsonConvert.DeserializeObject(reader.Value.ToString()) 但后来我收到了“System.NullReferenceException: Object reference not set to an instance of an object”跨度>
  • 他有一个生成的对象,用于他的完整 Json 字符串,不需要使用阅读器,他可以简单地将 JsonResponse 转换为生成的 CustomerVolumes 类
  • @Icepickle 我刚刚阅读了您上面的 jfiddle 评论,无视。谢谢!
  • @Rhurac 我收到:System.InvalidCastException:特定演员表无效。
猜你喜欢
  • 2013-06-03
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
相关资源
最近更新 更多