问题
I have to consume a so called web service implemented by a dumb monkey which is returning some garbage after the proper Json response. Something like this:
{
"Property1": 1,
"Property2": 2,
"Property3": 3
}<?xml version='1.0' ?>Maybe some other gibberish nonsense I wish to discard.
Now, I could just search for "<?xml"
and split, but I was wondering if I can use a stream reader or something to read up to the closing }
and then discard the rest.
I'm using C# and Json.Net.
回答1:
You can also set JsonSerializerSettings.CheckAdditionalContent = false to tell the serializer to ignore any content after the end of the deserialized JSON object:
var result = JsonConvert.DeserializeObject<Dictionary<string, long>>(json, new JsonSerializerSettings { CheckAdditionalContent = false })
Oddly enough it is necessary to do this explicitly despite the fact that the default value seems to be false
already, since the underlying field is nullable.
回答2:
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.
来源:https://stackoverflow.com/questions/37172263/discarding-garbage-characters-after-json-object-with-json-net