lawrencehagman
lawrencehagman

Reputation: 493

JSON parse error: Missing a name for object member

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.

Upvotes: 13

Views: 54603

Answers (4)

oVo
oVo

Reputation: 101

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.

Upvotes: 1

Alessandro
Alessandro

Reputation: 81

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);
    }
}

Upvotes: 0

lawrencehagman
lawrencehagman

Reputation: 493

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!

Upvotes: 14

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

Upvotes: 8

Related Questions