所以我有一个JSON
字符串,我只想读取一个特定的值.我如何Read me please!
从下面的字符串中选择" "?
var readString = /*Read me please!*/
JSON字符串:
"{\"aString\":\"Read me please!\"}"
为了更好地理解,我如何在这里做同样的事情?(只是" Read me please!
"):
"{\"Result\": { \"aString\":\"Read me please!\", \"anotherString\":\"Dont read me!\" } }"
如果两种方案都有不同的解决方案,我想知道两者.
PS:我不希望将值保存到object/class左右.只是暂时在里面var readString
.
你可以写一个模型:
public class MyModel { public string AString { get; set; } }
然后使用JSON序列化程序,如Json.NET:
string readString = "{\"aString\":\"Read me please!\"}"; MyModel model = JsonConvert.DeserializeObject(readString); Console.WriteLine(model.AString);
如果您不想使用第三方解决方案,可以使用内置JavaScriptSerializer
类:
string readString = "{\"aString\":\"Read me please!\"}"; MyModel model = new JavaScriptSerializer().Deserialize(readString); Console.WriteLine(model.AString);
现在假设你想要处理你的第二个JSON字符串,你可以简单地调整你的模型:
public class Wrapper { public MyModel Result { get; set; } } public class MyModel { public string AString { get; set; } public string AnotherString { get; set; } }
然后反序列化到这个包装类:
string readString = ... the JSON string in your second example ...; Wrapper wrapper = JsonConvert.DeserializeObject(readString); Console.WriteLine(wrapper.Result.AString); Console.WriteLine(wrapper.Result.AnotherString);
更新:
如果您不想反序列化到模型,您可以直接执行此操作:
string readString = "{\"aString\":\"Read me please!\"}"; var res = (JObject)JsonConvert.DeserializeObject(readString); Console.WriteLine(res.Value("aString"));
或者使用内置JavaScriptSerializer
类:
string readString = "{\"aString\":\"Read me please!\"}"; var serializer = new JavaScriptSerializer(); var res = (IDictionary)serializer.DeserializeObject(readString); Console.WriteLine(res["aString"]);