相关疑难解决方法(0)

从JToken获取可能不存在的价值(最佳实践)

使用Json.NET检索C#中甚至可能不存在的JSON值的最佳实践是什么?

现在我正在处理一个JSON提供程序,它返回有时包含某些键/值对的JSON,有时则不然.我一直在使用(也许是错误的)这个方法来获取我的值(例如获得一个double):

if(null != jToken["width"])
    width = double.Parse(jToken["width"].ToString());
else
    width = 100;
Run Code Online (Sandbox Code Playgroud)

现在它工作正常,但是当它们很多时它很麻烦.我最后编写了一个扩展方法,并且只有写完之后我才会想知道是否我是愚蠢的......反正这里是扩展方法(我只包括双和字符串的情况,但实际上我有很多更多):

public static T GetValue<T>(this JToken jToken, string key,
                            T defaultValue = default(T))
{
    T returnValue = defaultValue;

    if (jToken[key] != null)
    {
        object data = null;
        string sData = jToken[key].ToString();

        Type type = typeof(T);

        if (type is double)
            data = double.Parse(sData);
        else if (type is string)
            data = sData;

        if (null == data && type.IsValueType)
            throw new ArgumentException("Cannot parse type \"" …
Run Code Online (Sandbox Code Playgroud)

c# json.net

106
推荐指数
3
解决办法
11万
查看次数

有没有更好的方法将JObject强制转换为接口的任何实现?

我不确定是否有更好的方法来做到这一点.也许有人帮忙?

我想将一个类型的对象强制JObject转换为工厂中的类.类本身应该根据另一个参数来决定.但我只能想到将对象序列化为字符串并序列化为特定的类.一定有更好的方法?

https://dotnetfiddle.net/3Qwq6V

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace Test
{
    public class Input
    {
        public int TypeId { get; set; }
        public object ObjectDefinesInput;
    }

    public class VoiceInput
    {
        public string Language;
    }

    public class TextInput
    {
        public string Encoding;
    }

    public interface IResponse
    {
        void Respond();
    }

    public class VoiceResponse : IResponse
    {
        private VoiceInput input { get; set; }
        public VoiceResponse(VoiceInput input) { this.input = input; }

        public void Respond()
        {
            // use information …
Run Code Online (Sandbox Code Playgroud)

c#

6
推荐指数
1
解决办法
566
查看次数

标签 统计

c# ×2

json.net ×1