Json deserializer - c#

im currently making my first steep with json and well im complety confused.
I found many examples how to deserialize json files but nothing helps me.
{
"102": {
"id": 102,
"name": "cvmember3",
"profileIconId": 28,
"revisionDate": 1373593599000,
"summonerLevel": 1
},
"101": {
"id": 101,
"name": "IS1ec76a704e9b52",
"profileIconId": -1,
"revisionDate": 1355466175000,
"summonerLevel": 1
}
}
This is the json i object i got, the problem is im to stupid to deseralize it.
What i tried till now:
String name= (string) new JavaScriptSerializer().Deserialize<Dictionary<String, object>>(json)["name"];
Im missing the index, and dont know how to add it
anyone, can say me the correct line to deserialize, i has acces to the libary json.net

Alternatively you could define a class for the data you're going to get back and then parse your JSON into a dictionary something like this:
public class DataClass
{
public int id;
public string name;
public int profileIconId;
public long revisionDate;
public int summonerLevel;
}
Then
Dictionary<int, DataClass> myDictionary = JsonConvert.DeserializeObject<Dictionary<int, DataClass>>(json);
string foundName = myDictionary[102].name;

If you only want one item from the string (i only need to get one arttribut), you can use NewtonSoft to fish out the item you need:
using Newtonsoft.Json.Linq;
// read from where ever
string jstr = File.ReadAllText("C:\\Temp\\101.json");
JObject js = JObject.Parse(jstr);
var data102 = js["102"]["name"]; // == "cvmember3"
var data101 = js["101"]["name"]; // == "IS1ec76a704e9b52"
Console.WriteLine("Name for 101 is '{0}'", data101.ToString());
Console.WriteLine("Name for 102 is '{0}'", data102.ToString());
Output:
Name for 101 is 'IS1ec76a704e9b52'
Name for 102 is 'cvmember3'
This is a quick way to get at just one item value but it assumes you know what it looks like and where it is stored.

Related

Deserializing json without key name

i have json answer, like this, without key names, only values
[
[
1645724820000,
"35893.01000000",
"35898.38000000",
"35850.01000000",
"35876.07000000",
"10.19782000",
1645724879999,
"365831.59479120",
335,
"2.90744000",
"104298.60366850",
"0"
],
[
1645724880000,
"35876.79000000",
"35910.93000000",
"35864.93000000",
"35910.93000000",
"8.15710000",
1645724939999,
"292722.41648950",
326,
"3.18438000",
"114275.09871200",
"0"
]
]
i try deserializing with Newtonsoft, next C# code
public class Root
{
public List<List<String>> MyArray { get; set; }
}
//Root Pair = JsonConvert.DeserializeObject<Root>(Data2Json);
but it does't work, i'm begginer programmer, help pls, how i can deserializing it json. I guess it needs to be deserialized into some kind of array or list of values since there are no key names, but I don't know how, Google doesn't help anymore
you can try this code
List<List<string>> list = JsonConvert.DeserializeObject<List<List<string>>>(json);

Deserializing Json with unexpected characters in property

My application processes a Json that contains a list of objects. The properties of these objects are not completely known to me.
Example, in the following Json, only property "Id" is known to my application:
{"msgs": [
{
"Id": "Id1",
"A": "AAA"
},
{
"Id": "Id2",
"B": "BBB"
},
{
"Id": "Id3",
"C": "CCC"
}
]}
I want to parse these messages and extract the Id of each message. This has been working fine with the following code:
public class RootElem
{
[BsonElement("msgs")]
public List<JToken> Records { get; set; }
}
then read
var rootElem = JsonConvert.DeserializeObject<RootElem>(JSON_DATA);
Once I have my rootElem, I can iterate over each record in "Records" and extract the Id.
The problem is that sometime, some of the records will contain unexpected characters.
Example:
{
"Id": "Id2",
"B": "THIS CONTAINS UNEXPECTED DOUBLE QUOTE " WHAT SHOULD I DO?"
}
I tried adding error handling settings, but that didn't work:
var rootElem = JsonConvert.DeserializeObject<RootElem>(data, new JsonSerializerSettings
{
Error = HandleDeserializationError
});
private static void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
var currentError = errorArgs.ErrorContext.Error.Message;
Console.WriteLine(currentError);
errorArgs.ErrorContext.Handled = true;
}
I want to be able to access the rest of the records in the list, even if one/some of them contain these invalid chars. So I'm ok if "B" value of the 2nd record is return as null, or if the 2nd record is null altogether.
How can I achieve this?
p.s. I'm using Newtonsoft Json but I'm open to using other libraries.
The issue here is that what your application is receiving is not valid JSON, hence the errors you are seeing. The input should be properly escaped prior to being submitted to this method. If this is behind an HTTP API, the appropriate response would be a 400 as the request is not in a valid format. If you really need to work around this it's possible you could implement your own JsonConverter class and decorate the converting class with it, but this may not be possible as the JSON itself is invalid and the JsonReader is going to choke when it hits it.

I can´t find the track and trace number in my json string

I can´t find a value in a json string using json.net
I´ve tried jsonstr[0].track_numbers[0].track_number
This is my json file.
{
"0": {
"increment_id": "112",
"track_numbers": [
{
"track_number": "2223",
"title": "tit",
"carrier_code": "custom"
}
]
},
"live_shipping_status": "Delivered"
}
I want to find the Track_nummber.
dynamic jsonstr = JsonConvert.DeserializeObject(json));
var track = jsonstr[0].track_numbers[0].track_number
(donsent work)
The 0 of your json is a string key, not an index position:
dynamic obj = JsonConvert.DeserializeObject(json);
var trackNumber = obj["0"].track_numbers[0].track_number;
Note the difference in getting the first entry of track_numbers, which is an array.

Getting null values when deserializing a list using RestSharp

I am new to C# and to RestSharp.
I am writing a small program to retrieve a list of records via REST. I have been able to retrieve one record. Now I need to get a list of records, and here I have a problem.
The response I get using SoapUI looks like this:
{
"#count": 2,
"#start": 1,
"#totalcount": 2,
"Messages": [],
"ResourceName": "email",
"ReturnCode": 0,
"content": [
{"email": {"evsysseq": "0000000000000262"}},
{"email": {"evsysseq": "0000000000000263"}}
]
}
My code looks like this:
class EmailID
{
public string Evsysseq { get; set; }
}
var client = new RestClient("xxxxx");
client.Authenticator = new HttpBasicAuthenticator("xxx", "xxx");
string queryParm = HttpUtility.UrlEncode("evsysseq>\"0000000000000261\"");
var request = new RestRequest("xxxx?query="+ queryParm, Method.GET);
request.RootElement = "content";
var queryResult = client.Execute<List<EmailID>>(request).Data;
Running it does not result in errors, and I can see on the queryResult object that it does contain two records. But, Evsysseq is null on both, and that is my problem. I am not sure what to tweak to get it right.
You are getting null values because the JSON you are deserializing does not match the class structure you are deserializing into. You are telling RestSharp to deserialize the content array into a List<EmailID>, but the JSON really represents a list of objects that contain EmailID objects. And so you need another class:
class EmailObj
{
public EmailID Email { get; set; }
}
Then deserialize like this and you should get the data:
var queryResult = client.Execute<List<EmailObj>>(request).Data;
If you want to, you can then use LINQ to get the List<EmailID> that you originally wanted like this:
var emailIds = queryResult.Select(eo => eo.Email).ToList();
HTH

c# dynamic json objects with dynamic names question

Before I get flagged for duplicate, I have the code from Dynamic json object with numerical keys working quite well now. The question with my numeric keys is that unfortunately, the JSON string I am getting is initially delimited by year, so would I use reflection to attempt to create a dynamic property on a dynamic object, and if so how? I know with a dynamic object I can't have obj["2010"] or obj[0]. In JavaScript this is no problem, just trying to get it working in C#. Ideas?
Example of JSON being returned:
{
"2010": [
{
"type": "vacation",
"alloc": "90.00"
},
Alternatively, sometimes the year is the second element as such:
I have no control over this json.
{
"year": [],
"2010": [
{
"type": "vacation",
"alloc": "0.00"
},
Maybe I'm misunderstanding your question, but here's how I'd do it:
static void Main(string[] args) {
var json = #"
{
'2010': [
{
'type': 'vacation',
'alloc': '90.00'
},
{
'type': 'something',
'alloc': '80.00'
}
]}";
var jss = new JavaScriptSerializer();
var obj = jss.Deserialize<dynamic>(json);
Console.WriteLine(obj["2010"][0]["type"]);
Console.Read();
}
Does this help?
I wrote a blog post on serializing/deserializing JSON with .NET: Quick JSON Serialization/Deserialization in C#
I have up-voted the question and JP's answer and am glad I dug around the internet to find this.
I have included a separate answer to simplify my use case for others to benefit from. The crux of it is:
dynamic myObj = JObject.Parse("<....json....>");
// The following sets give the same result
// Names (off the root)
string countryName = myObj.CountryName;
// Gives the same as
string countryName = myObj["CountryName"];
// Nested (Country capital cities off the root)
string capitalName = myObj.Capital.Name;
// Gives the same as
string capitalName = myObj["Capital"]["Name"];
// Gives the same as
string capitalName = myObj.Capital["Name"];
Now it all seems quite obvious but I just did not think of it.
Thanks again.

Categories