0

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.

user3097695
  • 1,152
  • 2
  • 16
  • 42
  • The square bracket (`[`) in `[{\"sourceId\":1003 ..` represents the start of an array or list. You need a collection in the classes you deserialize into – Flydog57 Jul 03 '23 at 19:11
  • What problem are you having exactly? If you just need to know generally how to parse JSON in C# see [Read and parse a Json File in C#](https://stackoverflow.com/q/13297563/3744182). That being said, the value of `"data"` appears to be double-serialized JSON -- i.e. a its value is string representing an array that was previously serialized to JSON. Do you need to extract properties from it? – dbc Jul 03 '23 at 19:30
  • I am mainly confused by the double "{{" and "}}". – user3097695 Jul 03 '23 at 21:56

1 Answers1

1

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!

256Bits
  • 378
  • 1
  • 13
  • I think I found a way to solve the problem. `var subscriptionStream = _graphQlClient.CreateSubscriptionStream(request, ex => { Console.WriteLine(ex); }); _subscription = subscriptionStream.Subscribe( response => { var result = response.Data; }` – user3097695 Jul 05 '23 at 15:30
  • Although your answer did not directly solve the problem, it gave me some thoughts above solving the problem – user3097695 Jul 05 '23 at 15:38