Quantcast
Channel: Discarding garbage characters after json object with Json.Net - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by Alberto Chiesa for Discarding garbage characters after json object with Json.Net

$
0
0

I knew there had to be a simple and robust way:

    public T ReadTypeAndDiscardTheRest<T>(string json)    {        using (var sr = new StringReader(json))        using (var jsonReader = new JsonTextReader(sr))        {            var token = JToken.Load(jsonReader);            return token.ToObject<T>();        }    }    [Test]    public void TestJsonDiscarding()    {        var json = @"{""Key"":""a"", ""Value"":""n""}<?xml>aaaa";        var kp = ReadTypeAndDiscardTheRest<KeyValuePair<string, string>>(json);        Assert.That(kp.Key, Is.EqualTo("a"));        Assert.That(kp.Value, Is.EqualTo("n"));    }

As always, Json.Net FTW.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>