How to parse json file - c#

I have a problem with parsing
my json file:
[{
"username": "abc",
"number": "1",
"Coordinates": "3479087.7179635554,4723293.992024612,3587934.046241646,4936094.678770542"
},
{
"username": "ab",
"number": "2",
"Coordinates": "3638076.736796722,4693942.173163104,3669874.540563355,4955662.558011548"
}]
modal:
namespace WebUygAPI.Models
{
public class DrawInfo
{
public string username { get; set; }
public string number { get; set; }
public string coordinates { get; set; }
}
}
The problem I'm having in the controller is:
[HttpGet]
[Route("GetDraws")]
public async Task<IActionResult> get()
{
string filePath = #"C:\Users\Casper\source\repos\WebUygAPI\WebUygAPI\LineData.json";
using (StreamReader file = new StreamReader(filePath))
{
string o1 = file.ReadToEnd();
}
return Ok();
}
When I'm debugging I can see json file in o1 but I couldn't parse it.
I tried to parse but I had errors such as
newtonsoft.json.jsonreaderexception: unexpected character encountered while parsing value

I recommend this code
using Newtonsoft.Json;
var json = File.ReadAllText(filePath);
List<DrawInfo> info = JsonConvert.DeserializeObject<List<DrawInfo>>(json);

Related

Cannot deserealize Json string (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}"
}
]
}

How can I deserialize Array of Arrays in Newtonsoft Json C#? [duplicate]

I have this JSON:
[
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 1",
"Values": [
"Acc 1"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "1",
"Values": [
"1"
]
}
}
],
"Name": "account",
"Id": "1"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 2",
"Values": [
"Acc 2"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "2",
"Values": [
"2"
]
}
}
],
"Name": "account",
"Id": "2"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 3",
"Values": [
"Acc 3"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "3",
"Values": [
"3"
]
}
}
],
"Name": "account",
"Id": "2"
}
]
And I have these classes:
public class RetrieveMultipleResponse
{
public List<Attribute> Attributes { get; set; }
public string Name { get; set; }
public string Id { get; set; }
}
public class Value
{
[JsonProperty("Value")]
public string value { get; set; }
public List<string> Values { get; set; }
}
public class Attribute
{
public string Key { get; set; }
public Value Value { get; set; }
}
I am trying to deserialize the above JSON using the code below:
var objResponse1 = JsonConvert.DeserializeObject<RetrieveMultipleResponse>(JsonStr);
but I am getting this error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'test.Model.RetrieveMultipleResponse' because the type requires a JSON
object (e.g. {"name":"value"}) to deserialize correctly. To fix this
error either change the JSON to a JSON object (e.g. {"name":"value"})
or change the deserialized type to an array or a type that implements
a collection interface (e.g. ICollection, IList) like List that can
be deserialized from a JSON array. JsonArrayAttribute can also be
added to the type to force it to deserialize from a JSON array. Path
'', line 1, position 1.
Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
If one wants to support Generics (in an extension method) this is the pattern...
public static List<T> Deserialize<T>(this string SerializedJSONString)
{
var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
return stuff;
}
It is used like this:
var rc = new MyHttpClient(URL);
//This response is the JSON Array (see posts above)
var response = rc.SendRequest();
var data = response.Deserialize<MyClassType>();
MyClassType looks like this (must match name value pairs of JSON array)
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class MyClassType
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "Manager")]
public string Manager { get; set; }
[JsonProperty(PropertyName = "LastUpdate")]
public DateTime LastUpdate { get; set; }
}
Use NUGET to download Newtonsoft.Json add a reference where needed...
using Newtonsoft.Json;
Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));
return des.data.Count.ToString();
Deserializing JSON array into strongly typed .NET object
Use this, FrontData is JSON string:
var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);
and extract list:
var a = objResponse1[0];
var b = a.CustomerData;
To extract the first element (Key) try this method and it will be the same for the others :
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("Your URL"))
{
var apiResponse = await response.Content.ReadAsStringAsync();
var list = JObject.Parse(apiResponse)["Attributes"].Select(el => new { Key= (string)el["Key"] }).ToList();
var Keys= list.Select(p => p.Key).ToList();
}
}
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
worked!

need to loop the json string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
using the azure graph api to get the group members .i got the response in the following format:
{
"odata.metadata": "",
"value": [
{
"url": "https://graph.windows.net/myorganization/directoryObjects/5-93e1d09bdf66/Microsoft.DirectoryServices.User"
},
{
"url": "https://graph.windows.net/myorganization/directoryObjects/cb18b0aa-0ac6f51/Microsoft.DirectoryServices.User"
},
{
"url": "https://graph.windows.net/myorganization/directoryObjects/cf11211a06-ddee967505d8/Microsoft.DirectoryServices.User"
},
{
"url": "https://graph.windows.net/myorganization/directoryObjects/6a-bb9d-f08aee852c96/Microsoft.DirectoryServices.User"
},
{
"url": "https://graph.windows.net/myorganization/directoryObjects/62fce837ffb/Microsoft.DirectoryServices.User"
},
{
"url": "https://graph.windows.net/myorganization/directoryObjects/787cc75e-4726-89d/Microsoft.DirectoryServices.User"
},
{
"url": "https://graph.windows.net/myorganization/directoryObjects/26a2789b-2d/Microsoft.DirectoryServices.User"
},
{
"url": "https://graph.windows.net/myorganization/directoryObjects/6efcc6f2-333b-41e-6/Microsoft.DirectoryServices.User"
}
]
}
but not able to loop the rows inside the value field.i am using the c sharp programming
You just need to de-serialize the response string into a concrete POCO or for now you can de-serialize into a JObject and project the value property's url property.
Here's an example:
private static void Main(string[] args)
{
string response = #"
{
'odata.metadata': '',
'value': [
{
'url': 'https://graph.windows.net/myorganization/directoryObjects/5-93e1d09bdf66/Microsoft.DirectoryServices.User'
},
{
'url': 'https://graph.windows.net/myorganization/directoryObjects/cb18b0aa-0ac6f51/Microsoft.DirectoryServices.User'
},
{
'url': 'https://graph.windows.net/myorganization/directoryObjects/cf11211a06-ddee967505d8/Microsoft.DirectoryServices.User'
},
{
'url': 'https://graph.windows.net/myorganization/directoryObjects/6a-bb9d-f08aee852c96/Microsoft.DirectoryServices.User'
},
{
'url': 'https://graph.windows.net/myorganization/directoryObjects/62fce837ffb/Microsoft.DirectoryServices.User'
},
{
'url': 'https://graph.windows.net/myorganization/directoryObjects/787cc75e-4726-89d/Microsoft.DirectoryServices.User'
},
{
'url': 'https://graph.windows.net/myorganization/directoryObjects/26a2789b-2d/Microsoft.DirectoryServices.User'
},
{
'url': 'https://graph.windows.net/myorganization/directoryObjects/6efcc6f2-333b-41e-6/Microsoft.DirectoryServices.User'
}
]
}
";
JObject graphResponseObject = JsonConvert.DeserializeObject<JObject>(response);
IEnumerable<string> urls = graphResponseObject["value"]
.Select(x => x["url"].ToString());
foreach (string url in urls)
Console.WriteLine(url);
}
Outputting:
https://graph.windows.net/myorganization/directoryObjects/5-93e1d09bdf66/Microsoft.DirectoryServices.User
https://graph.windows.net/myorganization/directoryObjects/cb18b0aa-0ac6f51/Microsoft.DirectoryServices.User
https://graph.windows.net/myorganization/directoryObjects/cf11211a06-ddee967505d8/Microsoft.DirectoryServices.User
https://graph.windows.net/myorganization/directoryObjects/6a-bb9d-f08aee852c96/Microsoft.DirectoryServices.User
https://graph.windows.net/myorganization/directoryObjects/62fce837ffb/Microsoft.DirectoryServices.User
https://graph.windows.net/myorganization/directoryObjects/787cc75e-4726-89d/Microsoft.DirectoryServices.User
https://graph.windows.net/myorganization/directoryObjects/26a2789b-2d/Microsoft.DirectoryServices.User
https://graph.windows.net/myorganization/directoryObjects/6efcc6f2-333b-41e-6/Microsoft.DirectoryServices.User
Here's your POCO to get you started:
public class GraphResponse
{
[JsonProperty("odata.metadata")]
public string ODataMetaData { get; set; }
[JsonProperty("value")]
public IEnumerable<Value> Values { get; set; }
}
public class Value
{
[JsonProperty("url")]
public string Url { get; set; }
}
Write wrapper class for that JSON
public class Value
{
public string url { get; set; }
}
public class Example
{
public string odata.metadata { get; set; }
public IList<Value> value { get; set; }
}
Then deserialize the JSON string to the class type Example
var serializer = new Newtonsoft.Json.JsonSerializer();
var data = serializer.Deserialize<Example>(reader);
Create A class
public class Values
{
public string url { get; set; }
}
then this code
JObject jObject = JObject.Parse(JSONSTRING);
List<Values> values = JsonConvert.DeserializeObject<List<Values>>(jObject.GetValue("value").ToString());
foreach(var item in values)
{
Console.WriteLine(item.url);
}

Deserialise Json file with newtonsoft and query with linq

I'm new to Newtonsoft and I'm trying to deserialise my json file then query specific data points from it. Here is a sample of the json.
[
{
"reward_type": "1",
"rejected": "0",
"user_id": "538653",
"granted": "0"
},
{
"reward_type": "5",
"rejected": "0",
"user_id": "536345",
"granted": "1"
},
{
"reward_type": "5",
"rejected": "0",
"user_id": "539493",
"granted": "1"
}
]
I'm trying to query the values after each type. I've been trying to wrap my head around the documentation for Json.net for a few days, but I'm having trouble finding examples for deserializing files.
Here is what I've been using to parse the file.
InitializeComponent();
JArray adData1 = JArray.Parse(File.ReadAllText(#"c:\ads.json"));
using (StreamReader file = File.OpenText(#"c:\ads.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JsonSerializer serializer = new JsonSerializer();
JArray adData2 = (JArray)serializer.Deserialize(file, typeof(JArray));
JObject rewardType = (JObject)adData2[1];
label1.Text = rewardType.ToString();
}
Any help is appreciated.
From the suggestions:
Its only useable if the data have a common structure. You can Replace the DataTypes in the POCO, if you like
The POCO
public class Stuff {
public string reward_type { get; set; }
public string rejected { get; set; }
public string user_id { get; set; }
public string granted { get; set; }
}
How to use:
public void doThings() {
// var s = File.ReadAllText("yourfilename.json");
var s = #"{
""reward_type"": ""1"",
""rejected"": ""0"",
""user_id"": ""538653"",
""granted"": ""0""
},
{
""reward_type"": ""5"",
""rejected"": ""0"",
""user_id"": ""536345"",
""granted"": ""1""
},
{
""reward_type"": ""5"",
""rejected"": ""0"",
""user_id"": ""539493"",
""granted"": ""1""
}";
// [] is needed to make it recognize it as list
var listOfStuff = JsonConvert.DeserializeObject<List<Stuff>>("["+s+"]");
foreach (var item in listOfStuff)
{
Console.WriteLine(item.user_id);
}
}

Find a value from the json string in c#

This is my json string :
{"loginAccounts": [
{
"name": "abc",
"accountId": "123456",
"baseUrl": "https://abc.defghi.com/test/t12/remark/123456",
"isDefault": "true",
"userName": "Ceilina James",
"userId": "7c5bat57-850a-5c93-39eb-2015ai9o8822",
"email": "abc#test.com",
"siteDescription": ""
}
]}
I need "baseUrl" value. How to find it in the C# ?
You could use a JSON serializer such as the JavaScriptSerializer class to deserialize this JSON string to a C# class and then extract the required value. For example you could have the following model:
public class SomeModel
{
public LoginAccount[] LoginAccounts { get; set; }
}
public class LoginAccount
{
public string Name { get; set; }
public string AccountId { get; set; }
public string BaseUrl { get; set; }
public string IsDefault { get; set; }
...
}
and then:
string json = "... your JSON string comes here ...";
var serializer = new JavaScriptSerializer();
string json = ...
var model = (SomeModel)serializer.Deserialize(json);
foreach (var account in model.LoginAccounts)
{
string baseUrl = account.BaseUrl;
...
}
Using Json.Net
foreach (var acc in JObject.Parse(json)["loginAccounts"])
{
Console.WriteLine(acc["baseUrl"]);
}

Categories