Read specific value from JSON in C#

风流意气都作罢 提交于 2020-12-29 17:02:14

问题


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 string:

"{\"aString\":\"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: I do not wish to save the value into object/class or so. Just temporary inside var readString.


回答1:


You could write a model:

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

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);

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"));

or with the built-in JavaScriptSerializer class:

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



回答2:


var readString = JObject.Parse(str)["aString"];

Or for your second example:

var readString2 = JObject.Parse(str2)["Result"]["aString"];



回答3:


You have to use Newtonsoft (JSON.NET) to accomplish that. Then, you can access your json property this way:

var obj = JsonConvert.DeserializeObject(yourJson);
Console.WriteLine(obj.Result.aString); 



回答4:


Json.NET also provides a JSON reader if you don't want to deserialize the whole thing. For example:

string json = "{\"Result\":     {         \"aString\":\"Read me please!\",     \"anotherString\":\"Dont read me!\"     }            }";

using (var reader = new JsonTextReader(new StringReader(json)))
{
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "aString")
        {
            reader.Read();
            Console.Write(reader.Value);
            break;
        }

    }
}
Console.ReadKey();



回答5:


I played around with writing a generic method that can read any part of my json string. I tried a lot of the answers on this thread and it did not suit my need. So this is what I came up with. I use the following method in my service layer to read my configuration properties from the json string.

    public T getValue<T>(string json,string jsonPropertyName)
    {                      
        var parsedResult= JObject.Parse(json);

        return parsedResult.SelectToken(jsonPropertyName).ToObject<T>();
    }

and this is how you would use it :

    var result = service.getValue<List<string>>(json, "propertyName");

So you can use this to get specific properties within your json string and cast it to whatever you need it to be.



来源:https://stackoverflow.com/questions/41808673/read-specific-value-from-json-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!