Home > Back-end >  Not able to parse the object in C# .NET
Not able to parse the object in C# .NET

Time:02-05

I am not able to parse the below object in C# .NET. I am getting parsing object error.

messageBody (in String format - I am getting this below object in string format)

{
  "Type" : "Nti_1",
  "MessageId" : "c1b7cd5b-3099-532e-9539-91376eea607b",
  "SequenceNumber" : "10000000000000128000",
  "TopicArn" : "arn:aws:sns:us-east-1:xxxxxxx:Project1-SNS.fifo",
  "Message" : "{'Prop1':'202020','Prop2':'Hi-I again reached','Prop3':'Testing String'}",
  "Timestamp" : "2023-02-05T07:35:15.905Z",
  "UnsubscribeURL" : "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:xxxxxx:PushNotification-SNS.fifo:08d0fac2-ac0f-4ff9-b583-61024a98672d",
  "MessageAttributes" : {
    "EventType" : {"Type":"String.Array","Value":"["SMS","ArialRoot"]"}
  }
}

Below is the classes created to parse above object

public class ParentObject
{
    public string Type { get; set; }
    public string MessageId { get; set; }
    public string SequenceNumber { get; set; }

    public string TopicArn { get; set; }

    public ChildObject Message { get; set; }
    public string Timestamp { get; set; }

    public string UnsubscribeURL { get; set; }

    public string MessageAttributes { get; set; }
}


public class ChildObject
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

Below is the code which I am trying to parse the object

ParentObject obj = JsonConvert.DeserializeObject<ParentObject>(messageBody)

I dont know what I am missing to parse the string to specified above object.

CodePudding user response:

You need to create a C# class that matches the structure of the JSON

using Newtonsoft.Json;

public class MyClass
{
    public string Type { get; set; }
    public string MessageId { get; set; }
    public string SequenceNumber { get; set; }
    public string TopicArn { get; set; }
    public string Message { get; set; }
    public string Timestamp { get; set; }
    public string UnsubscribeURL { get; set; }
    public MessageAttributes MessageAttributes { get; set; }
}

public class MessageAttributes
{
    public EventType EventType { get; set; }
}

public class EventType
{
    public string Type { get; set; }
    public string Value { get; set; }
}

Deserialize the JSON string

MyClass obj = JsonConvert.DeserializeObject<MyClass>(json);

CodePudding user response:

MessageAttributes is a string in your .net type and an object in your json.

CodePudding user response:

Try this,

var parent = JsonConvert.DeserializeObject<ParentObject>(messageBody);
var child = JsonConvert.DeserializeObject<ChildObject>(parent.Message);
parent.Message = child;
  • Related