Search code examples
c#graphqljson.netdeserializationaws-appsync

How to parse json string from aws appsync subscription


I am working on the following classes:

    public class Change
{
    public string name { get; set; }
    public string messageName { get; set; }
    public string data { get; set; }
}

/**
 * Inside the object.data property received from AppSync is the onPublish result, of type Change.
 */
public class onPublishData
{
    public Change onPublish { get; set; }
}

/**
 * onPublishResult represents the object actually received when the subscription delivers a next value. The object
 * basically has a data property which in turn has an onPublish property which is a Change instance.
 */
public class onPublishResult
{
    public onPublishData data { get; set; }
}

with aws appSync api. The subscription returns the following json string:

  {{
 "onPublish": {
    "data": " 
  [{\"sourceId\":1003,\"reasonCode\":\"NoError\",
  \"changeType\":\"Updated\",\"data\":null,\"pId\":3,\"changeDateTime\":\"2023-07- 
   03T17:53:32.797452Z\",\"errorMessage\":null}]",
    "messageName": "reportStatusChange",
    "name": "*******"
  }
 }}

Basically, I need to populate above json string to onPublishResult object. Is there a way to do this? The code is C# code.


Solution

  • Try the Newtonsoft.Json NuGet package.

    You can use it in the following way:

    using static Newtonsoft.Json.JsonConvert;
    var result = DeserializeObject<onPublishResult>(jsonString);
    

    It may require some tweaking, (the doubled {{ and }} may confuse it), but it should be roughly what you are looking for.

    The following code should safely remove the doubled brackets:

    jsonString = jsonString.Replace("{{", "{").Replace("}}", "}")
    

    Happy coding!