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.
you json is not valid, you can fix it using replace string
messageBody = messageBody.Replace("\"[","[").Replace("]\"","]");
also you Message property is string, if you want to make it json you have to fix it too
messageBody = messageBody.Replace("'", "\"").Replace("\"{", "{").Replace("}\"", "}");
ParentObject obj = JsonConvert.DeserializeObject<ParentObject>(messageBody);
or you can fix a Message property using this code
JObject jObj = JObject.Parse(messageBody);
jObj["Message"] = JObject.Parse((string) jObj["Message"]);
ParentObject obj = jObj.ToObject<ParentObject>();
also fix the classes
public class ParentObject
{
public string Type { get; set; }
public string MessageId { get; set; }
public string SequenceNumber { get; set; }
public string TopicArn { get; set; }
public Message Message { get; set; }
public DateTime Timestamp { get; set; }
public string UnsubscribeURL { get; set; }
public MessageAttributes MessageAttributes { get; set; }
}
public class EventType
{
public string Type { get; set; }
public List<string> Value { get; set; }
}
public class MessageAttributes
{
public EventType EventType { get; set; }
}
public class Message
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
}
but it is better if you fix a message body in the source to this one
{
"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"]}
}
}
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);
MessageAttributes is a string in your .net type and an object in your json.
Try this,
var parent = JsonConvert.DeserializeObject<ParentObject>(messageBody);
var child = JsonConvert.DeserializeObject<ChildObject>(parent.Message);
parent.Message = child;
Related
Hello I have one json text inside this text there is one key which starts with $
string jsonText="{\"Version\":\"1.1\",\"Documents\":[{\"DocumentState\":\"Correct\",\"DocumentData\":{\"Name\":\"test\",\"$type\":\"Document\",\"Fields\":[{\"Name\":\"CustomerFullName\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"CustomerBirthDate\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentNumber\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0000000000\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"CustomerIsMarried\",\"$type\":\"Checkmark\",\"IsSuspicious\":false,\"Value\":true},{\"Name\":\"CustomerCounty\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"CustomerArea\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"CustomerAddress\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"11000000\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"DocumentGUID\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentProposalID\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentCountry\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"000\",\"RecognizedValue\":\"FRA\",\"Value\":\"FRA\"},{\"Name\":\"DocumentCurrency\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"000\",\"RecognizedValue\":\"EUR\",\"Value\":\"EUR\"},{\"Name\":\"DocumentTo\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentFrom\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentTotalNumberOfPages\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0\",\"RecognizedValue\":\"1\",\"Value\":\"1\"}]}}]}";
Console.WriteLine(jsonText);
var documentResult = JsonConvert.DeserializeObject<DocumentDTO>(jsonText);
and my class objects are below
public class DocumentDTO
{
public string Version { get; set; }
public List<DocumentInfo> Documents { get; set; }
}
public class DocumentInfo
{
public string DocumentState { get; set; }
public DocumentData DocumentData { get; set; }
public string DocumentAsBase64 { get; set; }
}
public class DocumentData
{
public string Name { get; set; }
[JsonPropertyName("$type")]
public string type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonPropertyName("$type")]
public string type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
but it is not working not converting $type to type. How can I solve this problem ?
Thanks in advance
Kind Regards
That's because you're using JsonConvert from Newtonsoft.Json library and are marking property with JsonPropertyName attribute from System.Text.Json.Serialization. The two just don't play well together. Try replacing your JsonPropertyName with JsonProperty attribute from Newtonsoft.Json and it should work.
public class DocumentData
{
public string Name { get; set; }
[JsonProperty("$type")]
public string Type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonProperty("$type")]
public string Type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
I have the following Json format returned from a WebAPI. Can you guys help to deserialize please?.
{
"#odata.context":"http://....... ","value":[
**{
"RecordNumber":"LDxxxx","RecordType":"Loan","PropertyAddress":{ "Address1":"601 xxxx","Address2":null,"Zip":"99999","City":"abc","State":"ab","County":"abcd" }
,"Summary":{ "BorrowerName":null,"ProductCode":null,"Status":"Not Registered" }
}**,{
"RecordNumber":"LDxxxx","RecordType":"Loan","PropertyAddress":{ "Address1":"601 xxxx","Address2":null,"Zip":"99999","City":"abc","State":"ab","County":"abcd" }
,"Summary":{ "BorrowerName":null,"ProductCode":null,"Status":"Not Registered" }
},
….]
}
I need what's in the value element. The bold is what is repeated in the return from API. I created a class that matches the description as below.
public class RootObject
{
[JsonProperty(PropertyName = "RecordNumber")]
public string RecordNumber { get; set; }
[JsonProperty(PropertyName = "RecordType")]
public string RecordType { get; set; }
[JsonProperty(PropertyName = "PropertyAddress")]
public PropertyAddress PropertyAddress { get; set; }
[JsonProperty(PropertyName = "Summary")]
public Summary Summary { get; set; }
}
Was able to skip the first record in the Json array using the following, got the "Value" part....but have not been successful in retrieving the "Value" object
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(forecast);
foreach (var kv in dict.Skip(1))
{
JArray jsonVal = JArray.Parse(kv.Value.ToString());
}
Appreciate your help.
Satya
You can deserialize to concrete classes (with the help of http://json2csharp.com/)
var result = JsonConvert.DeserializeObject<SOTest.Result>(json);
public class SOTest
{
public class PropertyAddress
{
public string Address1 { get; set; }
public object Address2 { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string State { get; set; }
public string County { get; set; }
}
public class Summary
{
public object BorrowerName { get; set; }
public object ProductCode { get; set; }
public string Status { get; set; }
}
public class Value
{
public string RecordNumber { get; set; }
public string RecordType { get; set; }
public PropertyAddress PropertyAddress { get; set; }
public Summary Summary { get; set; }
}
public class Result
{
[JsonProperty("#odata.context")]
public string Context { get; set; }
public List<Value> Value { get; set; }
}
}
This is my code:
dynamic resultObject = JsonConvert.DeserializeObject(Result);
string final = JsonConvert.SerializeObject(resultObject);
This my the result of final (JSON):
How do get the selling_price field? like doing final.selling_price?
My class:
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
} // itemPriceJson
You're not deserializing the json to a dynamic object properly. First of all, it's an array, not an object.
So, try it like this:
dynamic resultObject = JArray.Parse(Result); //Dynamic object.
var sellingPrice = resultObject[0].selling_price; //Get the selling price. Could also use some casting here.
You should change your class to
public class ItemPriceJson {
public int item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public int price_level_id { get; set; }
public string price_level_code { get; set; }
public int selling_price { get; set; }
} // itemPriceJson
and deserialize it with
var results = JsonConvert.DeserializeObject<List<ItemPriceJson>>( Result );
because the json result contains an array of objects and so you need a collection for deserialization
Create a POCO class which describes the object for example;
public class MyItemObject
{
public string item_price_id { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
}
Then use JsonConvert to deserialize a instance of the object.
var result = JsonConvert.DeserializeObject<MyItemObject>(json);
EDIT
As json is a list/collection deserialize as a list type;
var listResult = JsonConvert.DeserializeObject<List<MyItemObject>>(json);
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
}
And you can use the Newtonsoft json library
var result = JsonConvert.DeserializeObject<List<ItemPriceJson>>(jsonstring);
Guyz
I am trying to parse a JSON string into object. I have the below entity in which I am parsing the JSON string
public class Room : BaseEntity
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public string RoomListEmailAddress { get; set; }
public string MinimumXCoordinateInMap { get; set; }
public string MinimumYCoordinateInMap { get; set; }
public string MaximumXCoordinateInMap { get; set; }
public string MaximumYCoordinateInMap { get; set; }
public string RoomCapacity { get; set; }
public List<RoomImage> RoomImage { get; set; }
public string FloorName { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public InternalOnly InternalOnly { get; set; }
//public List<Equipment> Equipment { get; set; }
public override string ToString()
{
return this.Name;
}
}
public class RoomImage : BaseEntity
{
public string ImagePath { get; set; }
public string ImageType { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public InternalOnly InternalOnly { get; set; }
}
public class InternalOnly : BaseEntity
{
public string RoomId { get; set; }
public string FloorId { get; set; }
}
public class BaseEntity
{
}
I am using below method to parse the string into object
public static T ParseObjectToJSON<T>(string responseText)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(responseText)))
{
var rootObject = serializer.ReadObject(stream);
//return Convert.ChangeType(rootObject,typeof(T),System.Globalization.CultureInfo.CurrentCulture.TextInfo);
return (T)rootObject;
}
}
Below is the JSON string which I am trying to parse
https://docs.google.com/document/d/1k81M_UxIrXpHUPQNDUCHDfNw1wY7LM4mAaXjwpYMshk/edit?usp=sharing
The below json string is working
https://docs.google.com/document/d/1uQNwMmSyEZSolyxUVJl6gXzZPr6aRAf_WAogmUvVqt4/edit?usp=sharing
While parsing I get below error
The data contract type 'GAP.Entities.Room' cannot be deserialized because the member 'RoomImage' is not public. Making the member public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.
Note- RoomImage is marked public in the entity class. I get this error only when JSON string contains RoomImage array string otherwise no erro.
Any help is highly appreciated.
Thanks
Vinod
You can download and deserialize an JSON using Newtonsoft.
You have to reference the following DLL, and after that you can try this:
List<Room> deserializedObj = (List<Room>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, typeof(List<Room>));
The problem with your json is that if RoomImage has a single element, your service returns it as an object {} not as an array of objects [{}].
So If you want to use type-safe classes in your code(since dynamically accessing is also possible) you should pre-process your json before deserializing. Below code works (of course, as everybody says, using Json.Net)
string json = your__json__string
//PreProcess
var jobj = JObject.Parse(json);
foreach (var j in jobj["ObjectList"])
{
if (!(j["RoomImage"] is JArray))
{
j["RoomImage"] = new JArray(j["RoomImage"]);
}
}
var obj = JsonConvert.DeserializeObject<RootObject>(jobj.ToString());
public class InternalOnly
{
public string RoomId { get; set; }
public string FloorId { get; set; }
}
public class RoomImage
{
public string ImagePath { get; set; }
public string ImageType { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdateDate { get; set; }
public string LastUpdateId { get; set; }
}
public class ObjectList
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public string RoomListEmailAddress { get; set; }
public string MinimumXCoordinateInMap { get; set; }
public string MinimumYCoordinateInMap { get; set; }
public string MaximumXCoordinateInMap { get; set; }
public string MaximumYCoordinateInMap { get; set; }
public string RoomCapacity { get; set; }
public RoomImage[] RoomImage { get; set; }
public string FloorName { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public string IsRestrictedRoom { get; set; }
public InternalOnly InternalOnly { get; set; }
public object Equipment { get; set; }
}
public class RootObject
{
public List<ObjectList> ObjectList { get; set; }
}
The property RoomImage is public but your class probably isn't.
Make sure the RoomImage class is also marked public. That should solve the problem.
Alternatively use a library like JSON.NET that can do this deserialization without the need for public classes.
I have a JSON object like the following
{
"data": [
{
"id": "18128270850211_49239570772655",
"from": {
"name": "Someone Unimportant",
"id": "57583427"
}
/* more stuff */
}
]
}
I want to parse it using JSON.NET,
FacebookResponse<FacebookPost> response = JsonConvert.DeserializeObject<FacebookResponse<FacebookPost>>(json);
internal class FacebookResponse<T> where T : class
{
public IList<T> Data { get; set; }
public FacebookResponsePaging Paging { get; set; }
}
public class FacebookPost
{
public string Id { get; set; }
[JsonProperty("to.data.id")]
public string FeedId { get; set; }
[JsonProperty("from.id")]
public string UserId { get; set; }
[JsonProperty("created_time")]
public DateTime CreatedTime { get; set; }
[JsonProperty("updated_time")]
public DateTime UpdatedTime { get; set; }
public string Type { get; set; } // TODO: Type enum??
public string Message { get; set; }
public string Link { get; set; }
public string Name { get; set; }
public string Caption { get; set; }
public string Description { get; set; }
}
Everything comes through except for the FeedId and the UserId properties. How should I be mapping these?
public class From
{
public string name { get; set; }
public string id { get; set; }
}
public class Datum
{
public string id { get; set; }
public From from { get; set; }
}
public class FacebookPost
{
public List<Datum> data { get; set; }
}
internal class FacebookResponse<T> where T : class
{
public IList<T> Data { get; set; }
public FacebookResponsePaging Paging { get; set; }
}
FacebookResponse<FacebookPost> response = JsonConvert.DeserializeObject<FacebookResponse<FacebookPost>>(json);
Try below code :)
Use this site to get the object for .net
Then you can use JSON.Net to deserialize: ex.JsonConvert.DeserializeObject(input) iirc