JSON parse error: Missing a name for object member
Asked Answered
B

4

12

I'm new to json and trying to get a basic example working.

My http request returns {'username': '1'},{'username': '1'}.

I'm confused as to what valid json looks like but also how to get it into a string variable to deserialize.

Since ToJson returns {'username': '1'}, I figured the right thing to do was to put it in double quotes to convert it back.

I'm obviously missing something!

class DataItem{

    public string username;
}

string json = "{'username': '1'}";

deserialized = JsonUtility.FromJson<DataItem>(json);

Error: ArgumentException: JSON parse error: Missing a name for object member.

Begrime answered 9/8, 2016 at 17:23 Comment(3)
that's not valid json. json uses ", not 'Bang
Your original data input isn't valid JSON either. Arrays are denoted by the [ ] syntax.Urian
Thanks everyone, one of the points of confusion is why ToJson would return {'username': '1'} if {"username": "1"} is valid.Begrime
B
13

With very helpful responses I found what I was missing.

// Temp Data Struct
class DataItem{
    public string username;
    }

//Valid Json look like : {"username": "1"}

//Valid Json must be double quoted again when assigned to string var
// or escaped if you want 'valid' Json to be passed to the FromJson method
//string json = "{\"username\": \"1\"}"; or

string json = @"{""username"": ""1""}";

DataItem deserialized = JsonUtility.FromJson<DataItem>(json);

Debug.Log("Deserialized "+ deserialized.username);

Returns 'Deserialized 1'

Very basic stuff but thanks for helping me make sense of it!

Begrime answered 9/8, 2016 at 18:16 Comment(0)
C
7

Try to use double quotes(") to define keys.

Perhaps this reference at bellow may be useful.

https://www.rfc-editor.org/rfc/rfc7159#page-12

Caesarism answered 9/8, 2016 at 17:35 Comment(0)
J
0

You are missing the [SerializeField] on the class, the JSON string is valid. If you want double quotes you can use the escape \", so that it looks like this: "{\"username\": \"1\"}" but single quotes are just as good. The only thing you have to watch out for is when the string contains single quotes (in this case username's should not)

[SerializeField]    
public class DataItem{
    
    public string username;
}
    
public class YourMonoBehaviour: MonoBehaviour
{
    void Awake()
    {
        loadJson();
    }

    void loadJson()
    {
      string json = "{'username': '1'}";
    
      DataItem deserialized = JsonUtility.FromJson<DataItem>(json);
    }
}
Jacobs answered 24/8, 2020 at 18:14 Comment(0)
A
0

Good grief. This took me a while.

In my case, there was an extra "," in my json file. The last item doesn't have an extra comma. That's all.

Alameda answered 12/8 at 22:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.