使用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) 我不确定是否有更好的方法来做到这一点.也许有人帮忙?
我想将一个类型的对象强制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)