0
\$\begingroup\$

I'm trying to parse a very large JSON string in Unity. I do not need all the fields and I can't create a class with all the members.

It appears that all examples I have found, including the official docs, always deserialize and map every field to class members, which I cannot do for my application.

I tried creating a class that is similar to the JSON string, meaning that it has some members of the target JSON, just not all of them. But it's not working as desired: all members of my class are always undefined after deserializing.

Here's part of the string:

{
    "Robots":[{"CanReset":false,
    "CycleTime":123.875,
    "Info":null,
    "LevelInfo":null,
    "Name":"FTF_10033",
    "State":0,"
    ...
    }, ...
}

So I tried creating these classes:

[Serializable]
public class jsonData
{
    public Robot[] robots;
}

[Serializable]
public class Robot
{
    public string Name = "Unknown AGV";
}

And printing the results:

var jsonString = www.downloadHandler.text;
jsonData jsonData_ = JsonUtility.FromJson<jsonData>(jsonString);
Debug.Log("Json data: " + jsonData_);
Debug.Log("Robots: " + jsonData_.robots);

jsonData_ prints Json data: jsonData_, and jsonData_.robots prints nothing (just Robots:).

Is there any way to parse just these particular fields out of the JSON string?

I would be content with something like jsonString["robots"][0]["name"] or something.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Your JSON has an array called "Robots" but your class has an array called "robots" — those don't match. Do you still get this issue if you ensure an exact character-for-character match between your field names? \$\endgroup\$ – DMGregory Sep 30 '20 at 17:55
  • \$\begingroup\$ Oh my god... I think that was the issue... thank you! Edit: I can confirm that was the issue. What a dumb error, haha \$\endgroup\$ – mneumann Sep 30 '20 at 17:56
  • \$\begingroup\$ Want to edit your question to ask "How to deserialize a subset of fields from JSON" and post your correction as an answer below? \$\endgroup\$ – DMGregory Sep 30 '20 at 18:02
1
\$\begingroup\$

It looks like your problem is just a typo.

In the JSON, your array of robots is called "Robots" (uppercase R), but in your class you named it robots (lowercase R).

As long as the fields you want to deserialize are an exact character-for-character match in name, and a compatible type (ie. not trying to map an array to an integer or something silly like that), then what you're trying to do should work, even though you're not using all the fields specified in the JSON.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.