0

So in unity im getting the json parse error missing a name for object member in the console. I looked up similar cases and it seems to be that json has to be double quoted. So instead of my original simple "{"layout":"xxxxxx"}" json in my txt file I put "{""layout"":""xxxxxx""}" and now I get json parse error the document root must not follow by other values which I dont know what it means. Here is my relevant C# code

[Serializable]
public class ConfigData
{
    string layout;

} 

public class GM : MonoBehaviour {

public void Setup()
    {

      string path = "Assets/bricks.txt";
      string brickStr = File.ReadAllText (path);


      ConfigData configObj = new ConfigData ();
      configObj = JsonUtility.FromJson<ConfigData>(brickStr);
      Debug.Log ("serialized: " + configObj);
   }
}
  • Does `layout` need to be public? – dbc Mar 18 '18 at 01:34
  • Im just going straight off the documentation for json serialization https://docs.unity3d.com/Manual/JSONSerialization.html – Dominic Zenon Mar 18 '18 at 01:36
  • All the fields in that doc page are public, so give that a try. Also, the double-quoting `"{""layout"":""xxxxxx""}"` is only necessary when defining a string literal within your code; when loading from a file, the file contents should be `{"layout":"xxxxxx"}`. See http://www.json.org/ and http://json.org/example.html. You can also use https://jsonlint.com/ to ensure your test JSON is in a valid format. – dbc Mar 18 '18 at 01:44
  • ok I put it back to {"layout" : "xxxxxx" } in the text file. Making it private gave me an error though – Dominic Zenon Mar 18 '18 at 01:55
  • I meant to try making it `public`. In c# (or at least .Net c# which is what I know) by default fields are private. Is it different in unity? – dbc Mar 18 '18 at 01:57
  • no its the same. Private unless stated otherwise. I tried doing public string but its the same error – Dominic Zenon Mar 18 '18 at 02:14
  • 1
    Your json is likely invalid. Copy and post your json exactly as it is on your side. It will be better if you format the json like code in your question – Programmer Mar 18 '18 at 02:19
  • I got it working. I had an extra quotation. Thanks – Dominic Zenon Mar 18 '18 at 06:22
  • 1
    Closed since this is an invalid json. The duplicate has a section dedicated to errors with JsonUtility and a link to validate your json. I also want to let you know that you do not need this `new ConfigData ();`. The `FromJson` function should create new instance of that class for you. Basically you are creating new instance of `ConfigData` twice. Remove `new ConfigData ();` and set `configObj` to `null` before calling the `FromJson`. Finally, `"Assets/bricks.txt";` will fail when you build it. Use the resources folder for this. Test this game in a standalone build before moving on. – Programmer Mar 18 '18 at 12:44
  • ok thank you for the tips! – Dominic Zenon Mar 18 '18 at 19:27

0 Answers0