在C#中从JSON读取特定值 [英] Read specific value from JSON in C#

查看:387
本文介绍了在C#中从JSON读取特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个JSON字符串,我只想读取一个特定值.我该如何从下面的字符串中选择"Read me please!"?

So I have a JSON string where I just want to read a specific value. How do I just pick "Read me please!" from string below?

var readString = /*Read me please!*/

JSON字符串:

"{\"aString\":\"Read me please!\"}"

为了更好地理解,我该怎么做? (仅"Read me please!"):

For better understanding, how do I do the same here? (just "Read me please!"):

"{\"Result\":
    {    
    \"aString\":\"Read me please!\",
    \"anotherString\":\"Dont read me!\"
    }    
}"

如果两种选择都有不同的解决方案,我想两者都知道.

If both alternative have different solution I would like to know both.

PS:我不希望将值保存到对象/类中. var readString内只是临时的.

PS: I do not wish to save the value into object/class or so. Just temporary inside var readString.

推荐答案

您可以编写模型:

public class MyModel
{
    public string AString { get; set; }
}

,然后使用JSON序列化程序,例如 Json.NET :

and then use a JSON serializer such as Json.NET:

string readString = "{\"aString\":\"Read me please!\"}";
MyModel model = JsonConvert.DeserializeObject<MyModel>(readString);
Console.WriteLine(model.AString);

如果您不想使用第三方解决方案,则可以使用内置的

If you don't want to use third party solutions you could use the built-in JavaScriptSerializer class:

string readString = "{\"aString\":\"Read me please!\"}";
MyModel model = new JavaScriptSerializer().Deserialize<MyModel>(readString);
Console.WriteLine(model.AString);

现在假设您要处理第二个JSON字符串,您可以简单地修改模型:

Now assuming you want to handle your second JSON string you could simply adapt your model:

public class Wrapper
{
    public MyModel Result { get; set; }
}

public class MyModel
{
    public string AString { get; set; }
    public string AnotherString { get; set; }
}

然后反序列化此包装类:

and then deserialize to this wrapper class:

string readString = ... the JSON string in your second example ...;
Wrapper wrapper = JsonConvert.DeserializeObject<Wrapper>(readString);
Console.WriteLine(wrapper.Result.AString);
Console.WriteLine(wrapper.Result.AnotherString);


更新:


UPDATE:

如果您不想反序列化为模型,则可以直接执行以下操作:

And if you don't want to deserialize to a model you could directly do this:

string readString = "{\"aString\":\"Read me please!\"}";
var res = (JObject)JsonConvert.DeserializeObject(readString);
Console.WriteLine(res.Value<string>("aString"));

或内置的JavaScriptSerializer类:

string readString = "{\"aString\":\"Read me please!\"}";
var serializer = new JavaScriptSerializer();
var res = (IDictionary<string, object>)serializer.DeserializeObject(readString);
Console.WriteLine(res["aString"]);

这篇关于在C#中从JSON读取特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆