Search Unity

JsonUtility serializing issue

Discussion in 'Scripting' started by lmbarns, Jan 11, 2018.

  1. lmbarns

    lmbarns

    Joined:
    Jul 14, 2011
    Posts:
    1,628
    I've got a response json from Amazon AWS and I'm trying to serialize it back to a class and am not sure why it's not working. I've used the jsonUtility for arrays before and it was fine, I've searched through threads, and am stuck wondering if I need to use a different json serializer.

    This is the json I'm getting from the server

    These are the classes I made to serialize it to:
    Code (CSharp):
    1. [System.Serializable]
    2. public struct AWSResponse
    3. {
    4.     public string statusCode;
    5.     public body body;
    6.     public header headers;
    7. }
    8. [System.Serializable]
    9. public struct body
    10. {
    11.     public List<Item> Items;
    12.     public string Count;
    13.     public string ScannedCount;
    14.  
    15. }
    16.  
    17. [System.Serializable]
    18. public struct Item
    19. {
    20.     public string timedate;
    21.     public float latitude;
    22.     public string device;
    23.     public float longitude;
    24. }
    25. [System.Serializable]
    26. public struct header
    27. {
    28.     public string ContentType;
    29. }
    And when I try to serialize it, statusCode gets populated but nothing after that gets populated.

    Code (CSharp):
    1. AWSResponse resp = JsonUtility.FromJson<AWSResponse>(s);
    2.             print("Response Serialized: \nstatusCode: " + resp.statusCode
    3.             + " " + resp.body.Items.Count);
    Items count is 0 in the console.

    edit:: So after reconstructing it the opposite way (new instance and populate variables then serialize to json and compare strings) I noticed the json from amazon has "body": "{items stuff}" with the curly brackets in quotes and the jsonutility version doesn't, it's just "body": {} .
     
    Last edited: Jan 11, 2018
  2. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    So you need a string body and then you use JsonUtility once to deserialize the AWSResponse and again to convert the body string into an object?