How do I parse this json string - c#

I want to get the Cape URL but I'm having some trouble accessing It.
{
"timestamp": <java time in ms>,
"profileId": "<profile uuid>",
"profileName": "<player name>",
"signatureRequired": true, // Only present if ?unsigned=false is appended to url
"textures": {
"SKIN": {
"url": "<player skin URL>"
},
"CAPE": {
"url": "<player cape URL>"
}
}
}
I have tried multiple json methods but I can't figure out how to do it
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic dobj = jsonSerializer.Deserialize<dynamic>(thestring);
object result = dobj["textures"][0]["CAPE"][0]["url"];

It seem you are trying to treat the objects in your parsed json as some sort of array.
In both places where you've used [0], it is being done on an object. This would look for a key with the name 0 which doesn't exist.
Instead, you should just use the json keys directly.
Your final code should look something like this:
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic dobj = jsonSerializer.Deserialize<dynamic>(thestring);
object result = dobj["textures"]["CAPE"]["url"];

Related

Cannot access a jObject token in c#

I have the following json called 'originalJson'
{
"user_active": true,
"user_firstname": "Bob",
"user_lastname": "Tester",
"user_displayname": "Bobby",
"user_primary_email": "bob#tester.com",
"user_login_enabled": true,
"user_profile": {
"user_locale": "en-gb",
"user_lang": "en-gb"
},
"user_identities": [],
"user_roles": [
{
"app_id": "74a019c9-7171-4af0-a773-3984edaa35ca",
"context_uuid": "74a019c9-7171-4af0-a773-3984edaa35ca",
"context_type": "context_application",
"role_oid": "test_role_a",
"role_start_date": "2020-06-27T13:00:00Z",
"role_end_date": "2021-06-27T13:00:00Z"
}
]
}
and I am trying to replace the role_start_date and role_end_date values.
I have tried the following
JObject jObj = JObject.Parse(originalJson);
jObj["user_roles"]["role_start_date"] = somenewstartDate;
jObj["user_roles"]["role_end_date"] = somenewendDate;
However it is failing and doesn't like the "jObj["user_roles"]["role_start_date"]". I thought it would be pretty simple to do, I must be missing something.
Any ideas?
The property "user_roles" is an array of objects not a single object. You are trying to set a property value in the first entry in that array, so you need to do:
jObj["user_roles"][0]["role_start_date"] = somenewstartDate;
jObj["user_roles"][0]["role_end_date"] = somenewendDate;

JSON JObject.Parse modifies json string

I have got incomming Json in format:
{
"Type": "value",
"Name": "MeteoStation",
"UniqueAdress": "2C:3A:E8:0F:10:76",
"valuesList": [{
"Value": 23.00,
"Unit": "C",
"Type": "temperature",
"SourceUniqAdress": "2C:3A:E8:0F:10:76",
"TimeCaptured": "2018-03-26T09:36:13.200Z"
}]
}
In my program, I want to create object IValuePacket that is one value in list of values.
JObject jobject = JObject.Parse(incomingJson);
var settings = new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var incommingMessage = JsonConvert.DeserializeObject<MessageEncapsulation>(incomingJson);
string Type = incommingMessage.Type;
string name = incommingMessage.Name;
if (string.IsNullOrWhiteSpace(name))
name = "no name";
if (Type.ToLower().Equals("value")) {
var values = JsonConvert.DeserializeObject<List<IValuePacket>>(jobject["valuesList"].ToString());
}
Everything works fine untill I recieved exact this json as mention above.
JObject.Parse modifies value TimeCaptured and jobject looks like:
{
"Type": "value",
"Name": "Meteostation",
"UniqueAdress": "2C:3A:E8:0F:10:76",
"valuesList": [{
"Value": 23.00,
"Unit": "C",
"Type": "temperature",
"SourceUniqAdress": "2C:3A:E8:0F:10:76",
"TimeCaptured": "2018-03-26T09:36:13.2Z"
}]}
Thats not so much difference, but DateTime.ParseExact(value, "yyyy-MM-ddThh:mm:ss.fffZ", System.Globalization.CultureInfo.InvariantCulture); cannot parse new value. Actually, I am sending 201 ms instead of 200 ms. It works, but I want to have good time for future reasons.
Is there any way how to avoid changing in Json during parsing?
It does not really modify your string, it just parses your date string into DateTime object when you call JObject.Parse. If you do this:
var obj = JObject.Parse(json);
var values = (JArray) obj["valuesList"];
var time = (JValue) values[0]["TimeCaptured"];
Console.WriteLine(time.Value.GetType());
You notice that time.Value is of type DateTime. Then you do this:
JsonConvert.DeserializeObject<List<IValuePacket>>(jobject["valuesList"].ToString());
By doing that you convert valueList back to json, but now TimeCaptured is DateTime and not a string, so that DateTime object is converted to json string using whatever date time format is used by JSON.NET by default.
You can avoid parsing strings that look like dates to .NET DateTime objects by parsing json to JObject like this:
JObject obj;
using (var reader = new JsonTextReader(new StringReader(json))) {
// DateParseHandling.None is what you need
reader.DateParseHandling = DateParseHandling.None;
obj = JObject.Load(reader);
}
Then type of TimeCaptured will be string, as you expect.
Side note: there is no need to convert JToken back to string and then call JsonConvert.Deserialize on that string. Instead, do this:
var values = obj["valuesList"].ToObject<List<IValuePacket>>();

Complex json tree parsing

So I am given a json tree like the one below and I really just need to get the persons first and last names from here but I am having problems parsing the data.
{
"results":[
{
"id":{
"key":"Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable.json?api_key=",
"type":"Phone",
"uuid":"81dd6fef-a2e2-4b08-cfe3-bc7128b43786",
"durability":"Durable"
},
"line_type":"Landline",
"belongs_to":[
{
"id":{
"key":"Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable.json?api_key=",
"type":"Person",
"uuid":"1ffee2ef-cc88-4a1e-87b0-05349571b801",
"durability":"Durable"
},
"type":"Full",
"names":[
{
"salutation":null,
"first_name":"fred",
"middle_name":null,
"last_name":"jones",
"suffix":null,
"valid_for":null
}
],
"age_range":null,
"gender":null,
"locations":[
{
"id":{
"key":"Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable.json?api_key=",
"type":"Location",
"uuid":"bd4721f0-ba97-4ade-aac1-ed1f16be57ed",
"durability":"Durable"
},
"type":"Address",
"valid_for":{
"start":{
"year":2011,
"month":7,
"day":5
},
"stop":null
},
"legal_entities_at":null,
"city":"",
"postal_code":"",
"zip4":null,
"state_code":"",
"country_code":"",
"address":"",
"house":"10",
"street_name":"",
"street_type":"Ave",
"pre_dir":null,
"post_dir":null,
"apt_number":null,
"apt_type":null,
"box_number":null,
"is_receiving_mail":false,
"not_receiving_mail_reason":null,
"usage":null,
"delivery_point":null,
"box_type":null,
"address_type":null,
"lat_long":{
"latitude":,
"longitude",
"accuracy":"Street"
},
"is_deliverable":true,
"standard_address_line1":"",
"standard_address_line2":"",
"standard_address_location":"",
"is_historical":false,
"contact_type":"Home",
"contact_creation_date":1361177323
}
],
The code I have been using so far is:
string url = String.Format("https://proapi.whitepages.com/2.1/phone.json?api_key={0}&phone_number={1}", WhitePagesConstants.ApiKey, number);
using (WebClient webClient = new System.Net.WebClient())
{
WebClient n = new WebClient();
n.Encoding = System.Text.Encoding.UTF8;
var json = n.DownloadString(url);
Dictionary<string, Object> formattedjson = JsonConvert.DeserializeObject<Dictionary<string, Object>>(json);
}
I have been on this for too long and must finish it shortly so I ask please help me traverse this tree. I have never worked with json before and am quite lost on how to do this. The exact info I need is under "belongs_to" -> "names" -> first and last. I've changed some names to protect the innocent.
If all you need is to extract several properties, you can just navigate the path:
dynamic o = JsonConvert.DeserializeObject(json);
Console.WriteLine(o.results[0].belongs_to[0].names[0].first_name);
Console.WriteLine(o.results[0].belongs_to[0].names[0].last_name);
Or, if you prefer string dictionaries over dynamic objects:
JObject j = JsonConvert.DeserializeObject<JObject>(json);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["first_name"]);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["last_name"]);
P.S. Your JSON is broken. It would have been easier for me to test code if you provided a correct example.

Create javascript object which will convert to JSON then to Dictionary<string, bool>

I have a C# class which contains a property of Dictionary
I have a web-page which contains a list of items i need to cast into this dictionary.
My web-site will send the list up to my C# MVC application as JSON and then JsonConvert.Deserialise the JSON into my Dictionary object.
JsonConvert.Deserialise is expecting JSON in the following format:
"MyVariableName":{
"Item 1":true,
"Item 2":true
}
I need to know how i can construct this object in JavaScript.
So far, i have tried this without luck:
var items = [];
var v = $('#Items :input');
$.each(v, function(key, val) {
items.push({
key: val.value,
value: val.checked
});
});
JSON.stringify(v, null, 2);
But this returns a json converted value of:
"MyVariableName": [
{
"key": "Item 1",
"value": true
},
{
"key": "Item 2",
"value": true
}]
Which in turn does not de-serialize to my dictionary.
Thanks
Don't make an array; make an object:
var items = {};
$('#Items :input').each(function(i, val) {
items[val.value] = val.checked;
});
You have to use javascript serialization
One more thing you have different value int key, value pair like string and Boolean type, so you have to use Dictionary type.
And JavaScriptSerializerobject you will get System.Web.Script.Serialization name space of System.Web.Extensions.dll, v4.0.30319 assembly.
var jSerializer = new JavaScriptSerializer();
var newList= jSerializer.Deserialize<Dictionary<string,object>>(newData);

JSON trouble; deserialising to a datatable

I am trying to load JSON into a SQL database using JSON.net.
I've had no issues with other JSON responses however the following format doesn't seem to deserialise correctly.
{"Report":["2012m01d01","2012m01d02","2012w01","2012m01","2012m01d03","2012m01d04","2012m01d05","2012m01d06","2012m01d07","2012m01d08"],
"Realtime":null}
Could anybody provide some insight into why this would be? I'm using the following code to deserialise with.
public void Deserialize(String jsonText, ref DataTable dt)
{
JsonSerializer json = new JsonSerializer();
json.NullValueHandling = NullValueHandling.Ignore;
json.ObjectCreationHandling = ObjectCreationHandling.Replace;
json.MissingMemberHandling = MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
StringReader sr = new StringReader(jsonText);
JsonTextReader reader = new JsonTextReader(sr);
dt = (DataTable)json.Deserialize(reader, typeof(DataTable));
reader.Close();
}
Any ideas on what the best approach to solving this would be? This works fine with other JSON responses!
Thanks in advance
JSON is able to hold hirarchial information, that does not translate into a single datatable, but rather into several using a dataset and table relationships.
I put your json in http://jsonlint.com validator and formatter
you say this deserializes with no problems
{
"accountID": 1,
"profileID": null,
"name": "Pages",
"ID": "18d039ae0360",
"language": n‌​ull,
"type": null,
"Category": null,
"IsHierarchy": false,
"IntervalsEnabled": true,
"IsRe‌​altimeCompatible": true,
"properties": null
}
this is a single object
but this doesn't deserialize properly.
{
"Report": [
"2012m01d01",
"2012m01d02",
"2012w01",
"2012m01",
"2012m01d03",
"2012m01d04",
"2012m01d05",
"2012m01d06",
"2012m01d07",
"2012m01d08"
],
"Realtime": null
}
Actually your problem is data handling not serializion
the first is a single object and can be deserialized into a DataTable
and the other is an object that holds a reference to a list of report objects.
therefore you need to manually write a converter from your object to two dataTables
this code works, and i'm sure you can create a conversion function for your two tables
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error,
NullValueHandling = NullValueHandling.Include
};
JsonSerializer json = JsonSerializer.Create(settings);
json.Error += (x, y) =>
{
var s = y.ErrorContext;
var t = y.CurrentObject;
};
StringReader sr = new StringReader(jsonString);
JsonTextReader reader = new JsonTextReader(sr);
var o = json.Deserialize<ClsReport>(reader);
string sf = o.ReportItems[2];
Hope this helps

Categories

Resources