Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Error parsing JSON from remote server

Discussion in 'Scripting' started by viciousesque, Aug 6, 2016.

  1. viciousesque

    viciousesque

    Joined:
    Oct 4, 2014
    Posts:
    34
    I have a JSON file I can successfully parse via JsonUtility.FromJson when I fetch it locally from StreamingAssets, but fetching that same same file via WWW throws an error (ArgumentException: JSON parse error: Invalid value.) when I fetch it from a remote server.

    I can output both the local and remote files just prior to parsing by JsonUtility, and they are identical (I've even validated each in a JSON validator.)

    Here's the code I'm using to retrieve and parse the remote JSON:

    Code (CSharp):
    1. void Prime(){
    2.     string url = "https:content_url.json";
    3.     WWW www = new WWW(url);
    4.     StartCoroutine(WaitForContentJSON(www));
    5. }
    6.  
    7. IEnumerator WaitForContentJSON(WWW contentData)
    8. {
    9.     yield return contentData;
    10.  
    11.     // check for errors
    12.     if (contentData.error == null)
    13.     {
    14.         ParseJSON(contentData.text);
    15.  
    16.     } else {
    17.         Debug.Log("WWW Error: "+ contentData.error);
    18.     }
    19. }
    20.  
    21. void ParseJSON(string jsonString){
    22.     var ac = JsonUtility.FromJson<ArticlesCollection>(jsonString);
    23. }

    The error is thrown inside ParseJSON when invoking JsonUtility.FromJson

    Any help much appreciated.
     
  2. viciousesque

    viciousesque

    Joined:
    Oct 4, 2014
    Posts:
    34
    So the answer was as indicated in this post, http://answers.unity3d.com/questions/844423/wwwtext-not-reading-utf-8-text.html

    This is a verified fix for my issue.

    The issue seems to be that there are exactly 3 extra bytes on the head of the response. The fix is to use WWW.bytes instead of WWW.text, then slice off the extra 3 bytes. Thusly,

    Code (CSharp):
    1.  string jsonString;
    2. jsonString = System.Text.Encoding.UTF8.GetString(contentData.bytes, 3, contentData.bytes.Length - 3);
    It's particularly strange given ALL the documentation I could find indicated using WWW.text. Seems like Unity should add a data property to WWW that would solve this problem.

    BTW, I'm not using any additional plug-ins to work with the JSON (as I'm seeing pretty consistently referenced). I'm just parsing and working with the object in native Unity code via JsonUtility.FromJson