Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft Object serialized to String. JObject instance expected

Tags:

json

c#

Hi so am trying to parse this JSON line but i got some others that are like this in files thats why i want to automate this so i can remove the invalid lines to make the file a valid JSON for reading, The problem is that the JSON contains multiple JSON in 1 line

Example:

{"item":"value"}{"anotheritem":"value"}

Is there anyway to remove

{"anotheritem":"value"}

So it turns in to a valid JSON that is readable to start parsing the files

I tried doing using StreamReader cause there in a file i have multiple files that contain these invalid JSON

So i got it to be able to detect the Invalid JSON but for some reason i can't get it to read the JSON so i can use .remove to remove the invalid line

using (StreamReader r = new StreamReader(itemDir))
{
    string json = r.ReadToEnd();
    if (json.Contains("anotheritem"))
    {
        JObject NoGood = JObject.FromObject(json);
        MessageBox.Show(NoGood.ToString());
    }
}

The Error:

Object serialized to String. JObject instance expected.

Thank you all for your time and help.

like image 211
Premt Avatar asked Mar 09 '26 11:03

Premt


1 Answers

If each object are side by side without space or any other character, you can convert your string to an json array.

string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
string arrayValue = "[" + value.Replace("}{", "},{") + "]";
var array = JArray.Parse(arrayValue);
var goopArray = array.OfType<JObject>().Where(o => o.Property("anotheritem") == null);

⚠️ Edit : see my second answer. More robust solution. More modern. And support dotnet core builtin json serializer.

like image 135
Kalten Avatar answered Mar 11 '26 00:03

Kalten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!