This error appears under the following conditions
-
I have a JSON coming from an API, that looks like this. I have parsed this manually with JS’s JSON.parse and I am certain this is valid JSON:
{“Items”:[{“ID”:“0fcf745c-0501-4dac-a305-360eedab52c3”}]}
-
I auto-generated classes using http://json2csharp.com/ and those classes for models look like this:
public class Item
{
public string ID { get; set; }
}public class RootObject
{
public List Items { get; set; }
} -
I am using JsonUtility.FromJson to parse this JSON data from a string into this RootObject model:
var data = System.Text.RegularExpressions.Regex.Unescape(
Encoding.ASCII.GetString(responseObject.Response.Payload.ToArray())
);
// Confirmed: “data” when logged looks exactly like this:
// “{“Items”:[{“ID”:“0fcf745c-0501-4dac-a305-360eedab52c3”}]}”
RootObject data = JsonUtility.FromJson(data);
But nonetheless, I am relentlessly getting this error. I tried also manually using the System.Serializable flag and removing get; set; generated, as well as changing between structs and classes:
[System.Serializable]
public class Item
{
public string ID;
}
[System.Serializable]
public class RootObject
{
public List<Item> Items;
}
It does not appear to make any sense as to what is going on here. Additionally, this error is very unclear. The text says “The document root must not follow by other values.” Document root I assume means “Items”, in my case, and it most certainly is not followed by any other properties. It is of course “followed by” a value, i.e. the array of objects after it, but what good is a key-value pair without a value?
Here is the stack:
System.ArgumentException: JSON parse error: The document root must not follow by other values.
at (wrapper managed-to-native) UnityEngine.JsonUtility.FromJsonInternal(string,object,System.Type)
at UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) [0x0005c] in /Users/builduser/buildslave/unity/build/Modules/JSONSerialize/Public/JsonUtility.bindings.cs:42
at UnityEngine.JsonUtility.FromJson[T] (System.String json) [0x00001] in /Users/builduser/buildslave/unity/build/Modules/JSONSerialize/Public/JsonUtility.bindings.cs:30
If anyone has any insight into what I may be doing wrong here, it would be greatly appreciated. IMHO I think this might need to be a bug report filed to Unity, however, as I have gone through great lengths to ensure this JSON is valid. However, I am thinking the more likely scenario is that this error does not mean what it says (what is says doesn’t really mean anything anyway, as far as I can tell), and maybe there is something else wrong with it?
FWIW I also tried using UTF8 encoding instead of ASCII, and the reason I am using that Regex unescape line is because the API is sending escaped backslashes, which for some reason Unity doesn’t know how to handle if it helps at all, this JSON is a request being made through AWS SDK Lambda to an API Gateway endpoint.
Cheers and thanks friends,
Keith