Cannot deserealize Json string (C#) - c#

I have JSON string that came from AWS Lambda:
"body": "{'From': nemesises#live.com, 'To': suhomlin.eugene93#gmail.com}",
And try to deserialize it like this
var email = JsonConvert.DeserializeObject<SendEmailMessage>(emailRequest.Message);
Here is the class to what I need to deserialize
public class SendEmailMessage
{
public string From { get; set; }
public string To { get; set; }
public object Data { get; set; }
public int TemplateId { get; set; }
public List<string> Attachments { get; set; }
}
But I get this error
Newtonsoft.Json.JsonReaderException: Unexpected content while parsing JSON. Path 'From', line 1, position 11.
How I can solve this?

You need to wrap the entire json in {}.
{
"body": "{'From': nemesises#live.com, 'To': suhomlin.eugene93#gmail.com}"
}
You can use a site like https://jsonlint.com/ to work out things like this.

So the problem was in the format of the body
Here the correct format is
{
"Records": [
{
"messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
"receiptHandle": "MessageReceiptHandle",
"body": "{ \"Message\":\"{ 'from': 'nemesises#live.com','to': 'suhomlin.eugene93#gmail.com',}\"}",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1523232000000",
"SenderId": "123456789012",
"ApproximateFirstReceiveTimestamp": "1523232000001"
},
"messageAttributes": {},
"md5OfBody": "7b270e59b47ff90a553787216d55d91d",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:{partition}:sqs:{region}:123456789012:MyQueue",
"awsRegion": "{region}"
}
]
}

Related

Deserialize array from JSON in C#

So I am trying to deserialize an array from JSON into a C# class using Newtonsoft. I have seen tutorials and other questions on this, but I am running into problems as the array I want to get is not at the top level of the JSON. The JSON is structured like this, where I want to extract the "data" array and deserialize it:
"success": true,
"data": [
{
"key": "americanfootball_nfl",
"active": true,
"group": "American Football",
"details": "US Football",
"title": "NFL",
"has_outrights": false
},
{
"key": "aussierules_afl",
"active": true,
"group": "Aussie Rules",
"details": "Aussie Football",
"title": "AFL",
"has_outrights": false
},
{
"key": "basketball_euroleague",
"active": true,
"group": "Basketball",
"details": "Basketball Euroleague",
"title": "Basketball Euroleague",
"has_outrights": false
}
]}
I know that I first need to extract the data object from the JSON, and then parse that, but I am not too sure how. I have this class to deserialize the JSON:
public class SportsModel
{
public bool Success { get; set; }
public string Data { get; set; }
}
public class SportsData
{
public string Key { get; set; }
public bool Active { get; set; }
public string Group { get; set; }
public string Details { get; set; }
public string Title { get; set; }
public bool HasOutrights { get; set; }
}
And currently get the top level of the data using this:
SportsModel data = JsonConvert.DeserializeObject<SportsModel>(response);
I want to put the JSON array data into a list object, so that I can access it all
You only need to fix this part to make the serializer understand you're deserializing the Data field into a type of SportsData and not a string.
public class SportsModel
{
public bool Success { get; set; }
public List<SportsData> Data { get; set; }
}
Update
To get data into a list, I would assume you are referring to something of this nature
SportsModel result = JsonConvert.DeserializeObject<SportsModel>(response);
var sportsDataList = result.Data;
Your SportModels class needs to be updated to:
public class SportsModel
{
public bool Success { get; set; }
public List<SportsData> Data { get; set; }
}
SportsModel result = JsonConvert.DeserializeObject<SportsModel>(response);
And you will Data in a List.
What you can do is; go to visual studio and in edit menu menu and paste special
and click then paste json as class.
But first you need to copy the json string first.

Read Json string with Newtonsoft C#

I cannot read json string with c#. I getting error while reading.
Json file
{
"Invoice": {
"Description": "New",
"InvoiceTypeId": "3d166468-3923-11e6-9e7c-40e230cfb8ae",
"CustomerAccountsId": "TEST",
"InvoiceDate": "2016-06-27",
"PayableDate": "2016-06-27",
"Prefix": "A",
"Serial": "34222",
"tag": "TEST"
},
"InvoiceLine": [
{
"ValueId": "c41d3d85-3a1e-11e6-9e7c-40e230cfb8ae",
"Qantity": "3",
"UnitId": "a72e0dde-3953-11e6-9e7c-40e230cfb8ae",
"Price": "1.500,00",
"VatRateId": "18",
"LineVat": "810,00",
"LineTotal": "5.310,00",
"Vat": "00a239f1-3c3a-11e6-9e7c-40e230cfb8ae"
},
{
"ValueId": "fd11b236-3952-11e6-9e7c-40e230cfb8ae",
"Qantity": "5",
"UnitId": "a72e0dde-3953-11e6-9e7c-40e230cfb8ae",
"Price": "1.000,00",
"VatRateId": "18",
"LineVat": "900,00",
"LineTotal": "5.900,00",
"Vat": "00a239f1-3c3a-11e6-9e7c-40e230cfb8ae"
}
]
}
"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1."
JArray jsonVal = JArray.Parse(jsonArr) as JArray;
dynamic vars = jsonVal;
But everything right, I do not see bugs.
Don't do this...you're parsing to an array when it's clearly a complex object.
Use a converter such as Visual Studio or json2csharp.com to create the appropriate target object structure:
public class Invoice
{
public string Description { get; set; }
public string InvoiceTypeId { get; set; }
public string CustomerAccountsId { get; set; }
public string InvoiceDate { get; set; }
public string PayableDate { get; set; }
public string Prefix { get; set; }
public string Serial { get; set; }
public string tag { get; set; }
}
public class InvoiceLine
{
public string ValueId { get; set; }
public string Qantity { get; set; }
public string UnitId { get; set; }
public string Price { get; set; }
public string VatRateId { get; set; }
public string LineVat { get; set; }
public string LineTotal { get; set; }
public string Vat { get; set; }
}
public class Invoices
{
public Invoice Invoice { get; set; }
public List<InvoiceLine> InvoiceLine { get; set; }
}
Then simply use the JsonConvert methods to deserialize.
var parsedJson = JsonConvert.DeserializeObject<Invoices>(json);
You can also deserialize it to a dynamic object. Of course this is not ideal but if you don't want to create a whole new type for it, this would work
var vars =JsonConvert.DeserializeObject<dynamic>( jsonArr);
//vars.InvoiceLine
I noticed in the question and a comment you made, "How do I read this?" that you might also be confused on reading JSON which made the error message confusing to you.
You are trying to parse the object as a JArray while your JSON isn't for an array.
If you look at your error message,
"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1."
It's immediately throwing an error at the first character on the first line of your JSON and telling you it's not an array.
{ is the first character of your JSON, it was an array than it should start with [ just like if you were writing JavaScript.
Array:
var javaScriptArray = ["This", "Is", "An", "Array"];
Object:
var javaScriptObject = { id: 0, thisIsAnArray: false };
And put it together:
var javaScriptArrayOfObjects = [ { id: 0, thisIsAnArray: false},{ id: 1, thisIsAnArray: false} ];
You can see that when you look at your JSON (Java Script Object Notation) you should be able to tell if it's an array of objects or an object with arrays.
this should point you to it being a complex object and not an array and David L's answer covers that perfectly.
I just wanted to touch on better understanding the error message.

How to deserialize json string in windows phone?

I just got my json response as a string.My json is given below,
"code": 0,
"message": "success",
"students": {
"details":{
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}
}
}
Like hjeke and Second there are many key value pairs,how can i deserialize my json using Newtonsoft.json
Try to understand my solution in your previous question
How to deserialize json data in windows phone?
Your first JSON in that question was good and simple to use.
JSON, where field names are unique not convinient to deserialize. So, you got problems such as public class Hjeke and public class Second for each instance, when you use code generator.
Use JSON-structure with list of students:
"code": 0,
"message": "success",
"students": [
{
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
{
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}]
is good and flexible structure. Using this, you don't need to parse not obvious fields like
"details":{
"hjeke": {
and so on.
And work with them using classes, from my previous answer. The main idea - you need list of objects. public List<StudentDetails> students. Then, all students objects deserialized in List, which is easy to use.
As everybody mentioned your json seems to be very unflexible, huh.
You can extract the data you are interested in.
So this is your model:
public class StudentDetails
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
And this is how you can extract it:
var jsonObj = JObject.Parse(str);
// get JSON result objects into a list
var results = jsonObj["students"]["details"].Children().Values();
// serialize JSON results into .NET objects
var details = new List<StudentDetails>();
foreach (JToken result in results)
{
var st = result.ToString();
var searchResult = JsonConvert.DeserializeObject<StudentDetails>(st);
details.Add(searchResult);
}
I'm using a newtonsoft.json library here.
Your Response string has some mistakes man, its not a valid json
just small modification to be done as below:
{
"code": 0,
"message": "success",
"students": {
"details": {
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good"
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad"
}
}
}
}
you can make out the difference
Now Follow these steps:
1.Go to this link Json to C#
2.place your Json string there and generate C# class object
3.Now create this class in your solution
4.Now deserialize As below
var DeserialisedObject = JsonConvert.DeserializeObject<Your Class>(YourJsonString);
First, create the classes:
public class Hjeke
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Second
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Details
{
public List<Hjeke> hjeke { get; set; }
public List<Second> Second { get; set; }
}
public class Students
{
public List<Details> details { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string message { get; set; }
public List<Students> students { get; set; }
}
After that, use JSON.NET to deserialize:
var deserialized = JsonConvert.DeserializeObject<Class1>(YourStringHere);
Do you have any influence over the json response? Details should probably be a JSONArray in this case, not an object with a varying amount of properties, since I assume that's what you mean is the issue here.

JSON.NET won't deserialize into my object, throws an exception

My JSON (myString) looks like this:
"http://d.opencalais.com/dochash-1/0701d73f-2f99-39e1-8c29-e61ee8bf3238/cat/1":
{
"_typeGroup": "topics",
"category": "http://d.opencalais.com/cat/Calais/Law_Crime",
"classifierName": "Calais",
"categoryName": "Law_Crime",
"score": 0.869
}
I am trying to deserialise the above exact string into an object:
public class OpenCalaisResult
{
public string _typeGroup {get; set; }
public string category { get; set; }
public string categoryName { get; set; }
public string classifierName { get; set; }
public decimal score { get; set; }
}
I am trying this code:
OpenCalaisResult myObject = (OpenCalaisResult)JsonConvert.DeserializeObject(myString, typeof(OpenCalaisResult), settings);
I get an exception:
{"Error converting value
\"http://d.opencalais.com/dochash-1/0701d73f-2f99-39e1-8c29-e61ee8bf3238/cat/1\"
to type 'MyApp.Parsers.JsonTypes.OpenCalaisResult'. Path
'', line 1, position 78."}
Any idea what I am doing wrong?
your json should be like this
{
"http://d.opencalais.com/dochash-1/0701d73f-2f99-39e1-8c29-e61ee8bf3238/cat/1":
{
"_typeGroup": "topics",
"category": "http://d.opencalais.com/cat/Calais/Law_Crime",
"classifierName": "Calais",
"categoryName": "Law_Crime",
"score": 0.869
}
}
http://www.json.org/
Shows objects have the form ...
{ ... }
The form of your JSON is ...
x : { ... }
I'm guessing that 'x' is the type of the class being [de]serialised ... I don't believe it's supported by your library.
JSON support is a bit random.

Parsing multi-level JSON array

I'm trying to get objects from a multi-level JSON array. This is the an example table:
array(2) {
["asd"]=>
array(3) {
["id"]=>
int(777)
["profile"]=>
array(4) {
["username"]=>
string(5) "grega"
["email"]=>
string(18) "random#example.com"
["image"]=>
string(16) "http...image.jpg"
["age"]=>
int(26)
}
["name"]=>
string(5) "Grega"
}
["be"]=>
array(4) {
["username"]=>
string(5) "grega"
["email"]=>
string(18) "random#example.com"
["image"]=>
string(16) "http...image.jpg"
["age"]=>
int(26)
}
}
The string I'm trying to reach is either of the emails (example). This is how I try it:
public class getAsd
{
public string asd;
}
public class Profile
{
public string username { get; set; }
public string email { get; set; }
public string image { get; set; }
public string age { get; set; }
}
}
And then using JavaScriptSerilization.Deserilize<Asd>(jsonData); to deserilize it, but when I try the same with "Profile", it gives me the following error:
No parameterless constructor defined for type of 'System.String'.
JSON:
{"asd":{"id":777,"profile":{"username":"grega","email":"random#example.com","image":"http...image.jpg","age":26},"name":"Grega"},"be":{"username":"grega","email":"random#example.com","image":"http...image.jpg","age":26}}
And idea what might be wrong?
[EDIT: Smarm removed. OP did add JSON in an edit.]
Your profile class, as JSON, should resemble the following.
{
"username":"grega",
"email":"random#example.com",
"image":"http...image.jpg",
"age":"26",
"roles": [
{"name": "foo"},
{"name": "bar"}
]
}
array should not show up in JSON unless its part of a property name ("codearray") or property value("There's no 'array' in JSON. There's no 'array' in JSON.").
Arrays of objects in JSON are encased in square brackets [] and comma-delimited. An array/collection of profiles in JSON:
[
{
"username":"gretta",
"email":"mrshansel#example.com",
"image":"http...image.jpg",
"age":"37",
"roles": [
{"name": "foo"},
{"name": "bar"}
]
},
{
"username":"methusaleh",
"email":"old#men.org",
"image":"http...image.jpg",
"age":"2600",
"roles": [
{"name": "foo"},
{"name": "},
{"name": "bar"}
]
},
{
"username":"goldilocks",
"email":"porridge#bearshous.com",
"image":"http...image.jpg",
"age":"11",
"roles": [
{"name": "foo"}
]
}
]
While that may not fully answer your question, could you start with that and update your question?
EDIT:
See this answer by Hexxagonal for the complete approach.
Alright, here was what a "basic" version of your classes would be. You should really follow a standard of having properties have their first letter capitalized. Since you did not do this earlier, I maintained that style.
public class Type1
{
public TypeAsd asd { get; set; }
public TypeBe be { get; set; }
}
public class TypeAsd
{
public int id { get; set; }
public TypeBe profile { get; set; }
public string name { get; set; }
}
public class TypeBe
{
public string username { get; set; }
public string email { get; set; }
public string image { get; set; }
public int age { get; set; }
}
You deserialization code would then look something like the following:
string jsonString = "{\"asd\":{\"id\":777,\"profile\":{\"username\":\"grega\",\"email\":\"random#example.com\",\"image\":\"http...image.jpg\",\"age\":26},\"name\":\"Grega\"},\"be\":{\"username\":\"grega\",\"email\":\"random#example.com\",\"image\":\"http...image.jpg\",\"age\":26}}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
Type1 obj = serializer.Deserialize<Type1>(jsonString);

Categories