编程语言
首页 > 编程语言> > 从C#中的JSON读取特定值

从C#中的JSON读取特定值

作者:互联网

所以我有一个JSON字符串,我只想读取一个特定的值.我如何选择“请你读!”从下面的字符串?

var readString = /*Read me please!*/

JSON字符串:

"{\"aString\":\"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<MyModel>(readString);
Console.WriteLine(model.AString);

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

string readString = "{\"aString\":\"Read me please!\"}";
MyModel model = new JavaScriptSerializer().Deserialize<MyModel>(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<Wrapper>(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<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"]);

标签:json,c,net,json-deserialization
来源: https://codeday.me/bug/20190722/1501825.html