C# Error reading JObject from JsonReader. Path '', line 0, position 0

hlh3406 picture hlh3406 · Jul 2, 2019 · Viewed 10.5k times · Source

I'm trying to parse my json with the code below. I get the error:

Error reading JObject from JsonReader. Path '', line 0, position 0.

I thought this might be because my JSON was malformed, so I have output it, and it appears to be ok:

{ 
    "serviceDeskId": "4", 
    "requestTypeId": "223", 
    "requestFieldValues": { 
        "summary": "test" 
    } 
} 

But now I'm completely stuck. Can anyone see where I'm going wrong? This is driving me crazy!!

It's on this line that the error is triggered:

var jsonresponse = JObject.Parse(response);

Complete code snippet:

req.ContentType = "application/json";

                var json = JObject.Parse(
                        "{\"serviceDeskId\": \"4\",\"requestTypeId\": \"223\",\"requestFieldValues\": {\"summary\": \"" +
                        summary.Value + "\"}}");

                jsonCheck = json.ToString();

                using (var streamWriter = new StreamWriter(req.GetRequestStream()))
                    {

                        streamWriter.Write(json);
                    }

                    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;


                    // Obtain a 'Stream' object associated with the response object.
                    Stream ReceiveStream = resp.GetResponseStream();

                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

                    String response = "";

                    // Pipe the stream to a higher level stream reader with the required encoding format. 
                    StreamReader readStream = new StreamReader(ReceiveStream, encode);

                    response = readStream.ReadToEnd();

                    // Release the resources of stream object.
                    readStream.Close();

                    // Release the resources of response object.
                    resp.Close();

                    var jsonresponse = JObject.Parse(response);

Any help would be appreciated!

Answer

Paul Totzke picture Paul Totzke · Jan 12, 2021

I've only seen this error when the input is exactly empty string. Check that your text is making it to that varible.

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
                    
public class Program
{
    public static void Main()
    {
        var json = JObject.Parse("");
        Console.WriteLine(json);
        
    }
}

https://dotnetfiddle.net/u0FMLS