简体   繁体   中英

Detect end of json object using Newtonsoft.Json

I have a string that starts with a JSON object but after the end of which the string goes on (something like {"a":"fdfsd","b":5}ghresd ). The text afterward can contain any character and the JSON can be anything allowed for a JSON.

I would like to deserialize the JSON object and know where it ends because I want to process the rest of the string afterward, how do I do that, preferably using Newtonsoft.Json ?

You could make use of the SupportMultipleContent property, for example:

var json = "{\"a\":\"fdfsd\",\"b\":5}ghresd";

var reader = new JsonTextReader(new StringReader(json));
reader.SupportMultipleContent = true;

//Read the first JSON fragment
reader.Read();

var serializer = new JsonSerializer();
var result = serializer.Deserialize(reader);

//Or if you have a class to deserialise into:
//var result = serializer.Deserialize<YourClassHere>(reader);

//Line position is where the reader got up to in the JSON string
var extraData = json.Substring(reader.LinePosition);

This piece of code might not work as expected if your json has multiple lines:

var extraData = json.Substring(reader.LinePosition);

You might need to consider adding additional check:

if(reader.LineNumber != 1)
  throw new NotSupportedException("Multiline JSON objects are not supported.");

Or you can take that value from private field using Reflection :

var charPosition = (int)reader.GetType().GetField("_charPos", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(reader);

JsonTextReader source code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM