JSON data error Unity3d - c#

I'm currently busy with a project in Unity. For this project, I need to use and work with json data.
This is the json file:
{
"exerciseFrame": {
"currentFrameRate": 115.003,
"gestures": [],
"hands": [
{
"direction": [
-0.21788,
0.396045,
-0.892007
],
"id": 67,
"palmNormal": [
-0.207517,
-0.911865,
-0.354174
],
"palmPosition": [
76.5549,
114.137,
5.89759
],
"palmVelocity": [
11.5489,
-12.4382,
30.413
],
"r": [
[
0.985174,
0.0992006,
-0.139971
],
[
-0.110688,
0.990883,
-0.0768105
],
[
0.131075,
0.0911648,
0.987172
]
],
"s": 0.877737,
"sphereCenter": [
53.6198,
53.1508,
-39.351
],
"sphereRadius": 91.0197,
"stabilizedPalmPosition": [
74.1678,
112.23,
3.77527
],
"t": [
-20.2956,
10.8737,
19.0197
],
"timeVisible": 3.23297
}
],
"id": 470433,
"interactionBox": {
"center": [
0,
189,
0
],
"size": [
209.24,
209.24,
146.232
]
},
"pointables": [
{
"direction": [
-0.204191,
-0.171441,
-0.963802
],
"handId": 67,
"id": 83,
"length": 79.2433,
"stabilizedTipPosition": [
54.4213,
125.134,
-95.3633
],
"timeVisible": 1.79999,
"tipPosition": [
58.1631,
128.283,
-96.3226
],
"tipVelocity": [
11.7388,
-0.426162,
2.39705
],
"tool": false,
"touchDistance": 0.16562,
"touchZone": "hovering"
},
{
"direction": [
-0.128641,
0.0244301,
-0.99139
],
"handId": 67,
"id": 25,
"length": 73.593,
"stabilizedTipPosition": [
84.4969,
125.889,
-91.8182
],
"timeVisible": 1.40869,
"tipPosition": [
88.0132,
128.67,
-92.9798
],
"tipVelocity": [
9.78409,
-4.46077,
-10.2516
],
"tool": false,
"touchDistance": 0.0726596,
"touchZone": "hovering"
},
{
"direction": [
-0.231257,
-0.0952694,
-0.968217
],
"handId": 67,
"id": 62,
"length": 65.8749,
"stabilizedTipPosition": [
27.6915,
127.768,
-78.6761
],
"timeVisible": 0.913038,
"tipPosition": [
30.0744,
130.094,
-78.9935
],
"tipVelocity": [
11.5967,
-2.61466,
-3.92538
],
"tool": false,
"touchDistance": 0.123818,
"touchZone": "hovering"
},
{
"direction": [
-0.0484869,
0.109018,
-0.992857
],
"handId": 67,
"id": 73,
"length": 46.8336,
"stabilizedTipPosition": [
115.627,
114.182,
-61.4815
],
"timeVisible": 0.739126,
"tipPosition": [
118.889,
116.921,
-62.7602
],
"tipVelocity": [
2.0058,
-14.1922,
26.0571
],
"tool": false,
"touchDistance": 0.308196,
"touchZone": "hovering"
},
{
"direction": [
-0.757118,
0.0997547,
-0.645617
],
"handId": 67,
"id": 37,
"length": 47.2933,
"stabilizedTipPosition": [
-13.0828,
113.28,
3.91602
],
"timeVisible": 0.913038,
"tipPosition": [
-10.3237,
117.652,
2.30821
],
"tipVelocity": [
9.14501,
5.11948,
-3.45668
],
"tool": false,
"touchDistance": 0.0164196,
"touchZone": "hovering"
}
],
"r": [
[
0.564536,
0.157925,
-0.81016
],
[
0.200296,
-0.978399,
-0.0511501
],
[
-0.800738,
-0.133395,
-0.583973
]
],
"s": -443.531,
"t": [
22821.5,
-11650.1,
-3347.64
],
"timestamp": 5463086706
}
}
I have loaded it into unity with the following script (according this tutorial http://www.paultondeur.com/2010/03/23/tutorial-loading-and-parsing-external-xml-and-json-files-with-unity-part-2-json/)
using UnityEngine;
using LitJson;
using System;
using System.Collections;
public class LoadJSON : MonoBehaviour
{
IEnumerator Start()
{
//Load JSON data from a URL
string url = "http://localhost/project/application/exercise.json";
WWW www = new WWW(url);
//Load the data and yield (wait) till it's ready before we continue executing the rest of this method.
yield return www;
if (www.error == null)
{
//Process exercises found in JSON file
ProcessExercises(www.data);
}
else
{
Debug.Log("ERROR: " + www.error);
}
}
private void ProcessExercises(string jsonString)
{
Debug.Log (jsonString);
JsonData jsonExercise = JsonMapper.ToObject(jsonString); // convert json data to object.
Exercise exercise;
for(int i = 0; i<jsonExercise["exerciseFrame"].Count; i++) // for each exerciseFrame data in the .json file
{
Debug.Log(jsonExercise["exerciseFrame"].Count);
}
}
private void loadExercise(){
}
}`
It goes according to plan up until the line that is supposed to convert the json data to an object:
JsonData jsonExercise = JsonMapper.ToObject(jsonString); // convert json data to object.
I get the following error and I have no idea what is going wrong. Because jsonString is a string with data.
`ArgumentNullException: Argument cannot be null.
Parameter name: key
System.Collections.Generic.Dictionary`2[System.String,LitJson.PropertyMetadata].ContainsKey (System.String key) (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:458)
LitJson.JsonMapper.ReadValue (System.Type inst_type, LitJson.JsonReader reader)
LitJson.JsonMapper.ReadValue (System.Type inst_type, LitJson.JsonReader reader)
LitJson.JsonMapper.ReadValue (System.Type inst_type, LitJson.JsonReader reader)
LitJson.JsonMapper.ReadValue (System.Type inst_type, LitJson.JsonReader reader)
LitJson.JsonMapper.ToObject[JsonData] (System.String json)
LoadJSON.ProcessExercises (System.String jsonString) (at Assets/Scripts/JSON/LoadJSON.cs:32)
LoadJSON+<Start>c__Iterator1.MoveNext () (at Assets/Scripts/JSON/LoadJSON.cs:20)`
I really hope someone here can help me out. Thanks a lot for your time!

I found out what the problem was. The values of each variable should be a string as well. So in this case for example
"direction": [
-0.21788,
0.396045,
-0.892007
],
should be:
"direction": [
"-0.21788",
"0.396045",
"-0.892007"
],

Related

Why did my DISTINCT queries stop working in CosmosDB Data Explorer but works in C# API's?

I have some simple queries in a C# web API to my CosmosDB and the API works just fine but the same code copied from the C# code does not work any longer in the Azure Console as it used to
Query as follows
SELECT DISTINCT l.categories[0] as topLevelCat FROM c join l in c.locales
Error message is
Failed to query item for container hm-items: {"headers":{"x-ms-request-charge":0,"x-ms-documentdb-query-metrics":{}}}
This has always worked until I tried it today to try to write some new queries
What am I missing here?
Example Document below
{
"id": "0570eca0-8f16-4c85-a985-e3a271bcc6bc",
"_id": "5b07c2bfbc7407000122e8b4",
"artno": "0614460008",
"vendor": "Acme",
"updatedAt": "2019-06-25T18:50:33.167Z",
"locales": [
{
"title": "Gestreiftes T-Shirt",
"description": "Gestreiftes T-Shirt aus Baumwolljersey.",
"categories": [
"Herren",
"Große Größen",
"T-Shirts & Tanktops",
"T-Shirt"
],
"brand": null,
"images": [
],
"country": "DE",
"currency": "EUR",
"language": "de",
"variants": [
{
"artno": "0614460008005",
"urls": [
],
"price": 9.99,
"stock": 1,
"attributes": {
"size": "XL",
"color": "Schwarz/Weiß gestreift"
}
},
{
"artno": "0614460008002",
"urls": [
],
"price": 9.99,
"stock": 1,
"attributes": {
"size": "S",
"color": "Schwarz/Weiß gestreift"
}
},
{
"artno": "0614460008004",
"urls": [
],
"price": 9.99,
"stock": 1,
"attributes": {
"size": "L",
"color": "Schwarz/Weiß gestreift"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 9.99,
"stock": 1,
"attributes": {
"size": "XS",
"color": "Schwarz/Weiß gestreift"
}
},
{
"artno": "0614460008006",
"urls": [
],
"price": 9.99,
"stock": 1,
"attributes": {
"size": "XXL",
"color": "Schwarz/Weiß gestreift"
}
},
{
"artno": "0614460008003",
"urls": [
],
"price": 9.99,
"stock": 1,
"attributes": {
"size": "M",
"color": "Schwarz/Weiß gestreift"
}
}
]
},
{
"title": "Striped T-shirt",
"description": "Striped T-shirt in cotton jersey.",
"categories": [
"Men",
"T-shirts & Vests",
"Short Sleeve",
"T-shirt"
],
"brand": null,
"images": [
],
"country": "UK",
"currency": "GBP",
"language": "en",
"variants": [
{
"artno": "0614460008006",
"urls": [
],
"price": 8.99,
"stock": 1,
"attributes": {
"size": "XXL",
"color": "Black/White striped"
}
},
{
"artno": "0614460008005",
"urls": [
],
"price": 8.99,
"stock": 1,
"attributes": {
"size": "XL",
"color": "Black/White striped"
}
},
{
"artno": "0614460008004",
"urls": [
],
"price": 8.99,
"stock": 1,
"attributes": {
"size": "L",
"color": "Black/White striped"
}
},
{
"artno": "0614460008002",
"urls": [
],
"price": 8.99,
"stock": 1,
"attributes": {
"size": "S",
"color": "Black/White striped"
}
},
{
"artno": "0614460008003",
"urls": [
],
"price": 8.99,
"stock": 1,
"attributes": {
"size": "M",
"color": "Black/White striped"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 8.99,
"stock": 1,
"attributes": {
"size": "XS",
"color": "Black/White striped"
}
}
]
},
{
"title": "Randig t-shirt",
"description": "En randig t-shirt i bomullstrikå.",
"categories": [
"Herr",
"T-shirts & Linnen",
"Kortärmat",
"T-shirt"
],
"brand": null,
"images": [
],
"country": "SE",
"currency": "SEK",
"language": "sv",
"variants": [
{
"artno": "0614460008001",
"urls": [
],
"price": 99,
"stock": 1,
"attributes": {
"size": "XS",
"color": "Svart/Vitrandig"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 99,
"stock": 1,
"attributes": {
"size": "XL",
"color": "Svart/Vitrandig"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 99,
"stock": 1,
"attributes": {
"size": "S",
"color": "Svart/Vitrandig"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 99,
"stock": 1,
"attributes": {
"size": "XXL",
"color": "Svart/Vitrandig"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 99,
"stock": 1,
"attributes": {
"size": "M",
"color": "Svart/Vitrandig"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 99,
"stock": 1,
"attributes": {
"size": "L",
"color": "Svart/Vitrandig"
}
}
]
},
{
"title": "Striped T-shirt",
"description": "Striped T-shirt in cotton jersey.",
"categories": [
"Men",
"T-shirts & Tank tops",
"Short Sleeves",
"T-shirt"
],
"brand": null,
"images": [
],
"country": "US",
"currency": "USD",
"language": "en",
"variants": [
{
"artno": "0614460008001",
"urls": [
],
"price": 9.99,
"stock": 0,
"attributes": {
"size": "S",
"color": "Black/white striped"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 9.99,
"stock": 0,
"attributes": {
"size": "XL",
"color": "Black/white striped"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 9.99,
"stock": 0,
"attributes": {
"size": "M",
"color": "Black/white striped"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 9.99,
"stock": 0,
"attributes": {
"size": "L",
"color": "Black/white striped"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 9.99,
"stock": 0,
"attributes": {
"size": "XXL",
"color": "Black/white striped"
}
},
{
"artno": "0614460008001",
"urls": [
],
"price": 9.99,
"stock": 1,
"attributes": {
"size": "XS",
"color": "Black/white striped"
}
}
]
}
],
"relatedArtno": [
"0614460001",
"0614460002",
"0614460005",
"0614460006",
"0614460007",
"0614460011",
"0614460012"
],
"_rid": "QEwcAMCVWqgGAAAAAAAAAA==",
"_self": "dbs/QEwcAA==/colls/QEwcAMCVWqg=/docs/QEwcAMCVWqgGAAAAAAAAAA==/",
"_etag": "\"2e00f1ca-0000-0c00-0000-5d144d660000\"",
"_attachments": "attachments/",
"_ts": 1561611622
}
So I expect the output to be the unique top level categories for the locale I specify, for example country = 'DE' should give me the unique top level categories in 'DE' locale like Herren, Damen etc
From the cosmos db console, you could check the error code :
And locate the reason for the specific error referring to this document.
Based on your sql:
SELECT DISTINCT l.categories[0] as topLevelCat FROM c join l in c.locales
there is no syntax or format error in it, so please check the name of variables.
Test your sample data with sql:
SELECT DISTINCT l.categories[0] as topLevelCat,l.country FROM c join l in c.locales
Output:
It seems working.You mean it only broken when the locates never be defined?

How to count number of JSON elements of elements in C#

I have a json string items i.e,
{
"items": [
{
"kind": "youtube#playlistItem",
"etag": "\"uQc-MPTsstrHkWLmeNsM/NAYVM2gp_1c4XbQ9zYswb1-_gnk\"",
"id": "UExGS2IhV2ZJM2tZMTg2MWZZeDR2cS41NEM3RjdGQ0FDRjkwNUQ5",
"snippet": {
"publishedAt": "2017-03-21T20:38:22.000Z",
"channelId": "UCRUNoQu8kdtsY94D9MZ_sXA",
"title": "News Plus 21-03-17",
"description": "News Plus 21-03-17",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/FIXv7nmU/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/FFynmU/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/FIXvnmU/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "",
"playlistId": "PLFKb5r-iLUmbOhkY1861fYx4vq",
"position": 0,
"resourceId": {
"kind": "youtube#video",
"videoId": "FIXvFylfjwmU"
}
}
},
{
"kind": "youtube#playlistItem",
"etag": "\"uQc-MPTsstrHkeNsM/TKjx1_sGvJVB3tX8cFnxsE\"",
"id": "UExGS2I1ci1pTFVtYk9oc2htryhjrtUNBMTM5RDMyREQ5",
"snippet": {
"publishedAt": "2017-03-21T19:34:48.000Z",
"channelId": "UCtsY94D9MZ_sXA",
"title": "Private video",
"description": "This video is private.",
"channelTitle": "Capital TV",
"playlistId": "PLFKb5r-iLUmbOh861fYx4vq",
"position": 1,
"resourceId": {
"kind": "youtube#video",
"videoId": "VQ1rDS59318"
}
}
},
{
"kind": "youtube#playlistItem",
"etag": "\"uQc-MPTsstrHkWLmeNsM/JXH9kcF8my3r2Yl0OPK3U\"",
"id": "UExGS2I1ci1pTFVtYhV2ZJM2tZMTg2MWZZeDR2BBNzZCQzY5MDk4",
"snippet": {
"publishedAt": "2017-03-21T19:06:41.000Z",
"channelId": "UCRUNtrhjsY94D9MZ_sXA",
"title": "Director NAB Corruption Scandal",
"description": "",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/BCnejgyQ/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/BCnejyQ/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/BCneyQ/hqdault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Capital TV",
"playlistId": "PLFKb5r-iLUmbOhkY1861fYx4vq",
"position": 2,
"resourceId": {
"kind": "youtube#video",
"videoId": "BCnhtjty2gyQ"
}
}
}
}
]
}
As items has two elements, But I want to count the number of element present in snippet, how can I count, I have parse the json and try to get length as,
dynamic result = JsonConvert.DeserializeObject("jsonStr");
foreach (var res in result.items)
{
int size = res.snippet.count; // Not working
}
(res.snippet as JObject).Count
Slightly different syntax to aspark's solution,
private static void Main(string[] args)
{
string json = #"
{
a: 1,
b: 2,
c: [
{c1: 'asdas', c2:231},
{c1: 'aaaaaa', c2: 100},
{c1: 'x', c2: 83823}
]
}
";
Console.WriteLine(JObject.Parse(json)["c"].Count());
//following also works
Console.WriteLine(o.Property("c").Value.Count());
//both print 3
}

Handling double quotes in JSON strings

We have an application with knockout and we are facing a problem that some registers in the database have double quotes, which caused JSON parsing to fail.
Here's my json that is not valid due to a rogue double quote:
{
"OptionSummaries": [
{
"Id": 110,
"Name": "Option 1",
"Status": 1,
"ProductGroupNodes": [
{
"Id": 110,
"Name": "Corporate Brand Reputation",
"Status": 2,
"Waves": [
{
"Id": 110,
"Name": "Wave 1",
"Status": 2,
"Services": [
{
"Id": 1101,
"Title": "Proposal Budget Owner Service",
"CurrencyCode": "USD",
"EstimatedCost": 177.0000,
"CreationDateTime": "/Date(1437472898503)/",
"Status": 2
}
]
}
]
},
{
"Id": 111,
"Name": "2013 Consumer Scan",
"Status": 1,
"Waves": [
{
"Id": 111,
"Name": "Wave 1",
"Status": 1,
"Services": [
{
"Id": 1111,
"Title": "Proposal Budget Owner Service",
"CurrencyCode": "USD",
"EstimatedCost": 0.0000,
"CreationDateTime": "/Date(1437472898503)/",
"Status": 1
}
]
}
]
}
]
},
{
"Id": 115,
"Name": "Option 2",
"Status": 1,
"ProductGroupNodes": [
{
"Id": 115,
"Name": "Corporate Brand Reputation",
"Status": 1,
"Waves": [
{
"Id": 115,
"Name": "Wave 1",
"Status": 1,
"Services": [
{
"Id": 1151,
"Title": "Proposal Budget Owner Service",
"CurrencyCode": "USD",
"EstimatedCost": 0.0000,
"CreationDateTime": "/Date(1437472898503)/",
"Status": 1
}
]
}
]
},
{
"Id": 116,
"Name": "2013 Consumer Scan",
"Status": 1,
"Waves": [
{
"Id": 116,
"Name": "Wave 1",
"Status": 1,
"Services": [
{
"Id": 1161,
"Title": "Proposal Budget Owner Service",
"CurrencyCode": "USD",
"EstimatedCost": 0.0000,
"CreationDateTime": "/Date(1437472898503)/",
"Status": 1
}
]
}
]
}
]
}
],
"ServiceCostsEdit": {
"ServiceId": 1101,
"ServiceName": "Proposal Budget Owner Service",
"ServiceCurrencyIsoCode": "USD",
"ServiceLegalEntityCode": "0310",
"LaborHourCostsPanel": {
"LaborHourCosts": [
{
"Id": 2,
"CostCenters": [
{
"Disabled": false,
"Group": null,
"Selected": false,
"Text": "3101010001 - Consumer KAM Group",
"Value": "3101010001"
},
{
"Disabled": false,
"Group": null,
"Selected": false,
"Text": "3102510255 - Knowledge Panel",
"Value": "3102510255"
}
],
"FiscalYears": [
{
"Disabled": false,
"Group": null,
"Selected": false,
"Text": "2013",
"Value": "2013"
}
],
"LaborGrades": [
{
"Code": "0HL002",
"CurrencyCode": "USD",
"Rate": 44.0000,
"Disabled": false,
"Group": null,
"Selected": false,
"Text": "0HL002 - 44.00/hr USD",
"Value": "0HL002"
}
],
"SelectedLaborGradeCostCenter": "3101010001",
"SelectedLaborGradeFiscalYear": 2013,
"SelectedLaborGradeCode": "0HL002",
"SelectedLaborGradeRate": 44.0000,
"SetupHours": 2.00,
"ManagementHours": 1.00,
"DeliveryHours": 1.00,
"IsEmpty": false
}
],
"LaborHourCostsCostCenterDataSource": [
{
"Disabled": false,
"Group": null,
"Selected": false,
"Text": "3101010001 - Consumer KAM Group",
"Value": "3101010001"
},
{
"Disabled": false,
"Group": null,
"Selected": false,
"Text": "3102510255 - Knowledge Panel",
"Value": "3102510255"
}
],
"DefaultCostCenterCodeForInitialEmptyRecord": null,
"DefaultFiscalYearForInitialEmptyRecord": null,
"OverheadCosts": [
{
"LaborGradeCostCenterCode": "3101010001",
"LaborGradeFiscalYear": 2013,
"OverheadRate": 0.0000,
"SetupHours": 2.00,
"ManagementHours": 1.00,
"DeliveryHours": 1.00
}
],
"OverheadCostsVisible": true,
"OverheadCostsInitialDataSource": [
{
"Key": {
"CostCenterCode": "3101010001",
"FiscalYear": 2013
},
"Value": {
"Code": "0HO001",
"CurrencyCode": "USD",
"Rate": 0.00,
"Disabled": false,
"Group": null,
"Selected": false,
"Text": "0HO001 - USD 0.00/hr",
"Value": "0HO001"
}
}
],
"CostCenter": "F2F PAPI",
"ServiceCurrencyIsoCode": "USD",
"EditingAllowed": true
},
"VendorCostsPanel": {
"VendorCosts": [
{
"Id": 132,
"SelectedCostElementCode": "1992000004",
"VendorCode": "",
"VendorName": null,
"Description": "doublequotes"","DirectCostAttachment":null,"Quantity":1,"VendorRate":1.0000,"IsEmpty":false}],"CostElements":[{"Disabled":false,"Group":null,"Selected":false,"Text":"ExternalSuppliercosts","Value":"1992000004"},{"Disabled":false,"Group":null,"Selected":false,"Text":"Licensesfromaffilitatedcompanies","Value":"1992000002"}],"ServiceCurrencyIsoCode":"USD","EditingAllowed":true},"CostingAssumptionsPanel":{"Description":"","EditingAllowed":true},"ServiceSpecificationsPanel":{"Title":"ProposalBudgetOwnerService","Type":"ProposalBudgetOwnerService","Fields":[{"Value":"Hellolonglonglongtext...","Id":153,"Code":"OVERVIEW","Title":"Overview","IsRequiredForCosting":false,"DependencyVisibilityExpression":null,"FieldCodesToReevaluateOnChange":[],"EditingAllowed":false}]},"ApprovalComments":{"CommentType":0,"Message":null,"ApproverName":null,"ApproverEmail":null,"AnyComments":false},"RejectedCostInfoVisible":false,"EditingAllowed":true},"SubmitCostsEnabled":true,"EditingAllowed":false,"SelectedTreeNode":{"Id":1101,"Type":3},"Proposal":{"ProposalId":11,"ProposalName":"Ad-hocatCostingonMain","ProposalCostCenterCode":"3102510220","ProposalValid":{"IsValid":true,"ErrorMessage":""},"SoldToCustomer":"JenniferSamson","ExpectedProjectStartDate":"/Date(1426892400000)/","ExpectedProjectEndDate":"/Date(1431208800000)/","FunctionalityAreaEnabled":true}}
If you test this json against jsonlint you will see where the problem lies. What is the best way to handle this? I think the way I'm serializing the C# model to JSON is not proper? To do that I use:
var jsonModel = JsonConvert.SerializeObject(Model);
Any help is very appreciated.
EDIT
Issue was fixed. Problem was with the serialization.
I fixed this by using the method HttpUtility.JavaScriptStringEncode
var jsonViewModel = HttpUtility.JavaScriptStringEncode(Json.Encode(Model));
This solved my problem. All I had to do to pass this to knockout was #Html.Raw(jsonViewModel)
Best regards and thanks everyone!
Daniel

JToken get a specific value

I have following JToken output. How can I retrieve the 'value' here from TenantID which should be 1 in this case?
{[
{
"value": 1,
"metadata": {
"userType": 0,
"flags": 8,
"type": {
"type": "INT4",
"name": "Int",
"id": 56
},
"colName": "TenantID"
}
}
]}
This is my current code :
JToken value;
if (usr.Profile.TryGetValue("tenantid", out value))
{
JObject inner = value["value"].Value<JObject>(); //not working with null error
User.TenantID = (string)value;
}
User.obj = usr.Profile;
EDIT - please find below the complete JToken output :
{[
{
"value": 1,
"metadata": {
"userType": 0,
"flags": 8,
"type": {
"type": "INT4",
"name": "Int",
"id": 56
},
"colName": "TenantID"
}
}
]}
Count: 1
First (Newtonsoft.Json.Linq.JContainer): {{
"value": 1,
"metadata": {
"userType": 0,
"flags": 8,
"type": {
"type": "INT4",
"name": "Int",
"id": 56
},
"colName": "TenantID"
}
}}
First (Newtonsoft.Json.Linq.JToken): {{
"value": 1,
"metadata": {
"userType": 0,
"flags": 8,
"type": {
"type": "INT4",
"name": "Int",
"id": 56
},
"colName": "TenantID"
}
}}
HasValues: true
IsReadOnly: false
Last (Newtonsoft.Json.Linq.JContainer): {{
`"value": 1,
"metadata": {
"userType": 0,
"flags": 8,
"type": {
"type": "INT4",
"name": "Int",
"id": 56
},
"colName": "TenantID"
}
}}
Last (Newtonsoft.Json.Linq.JToken): {{
"value": 1,
"metadata": {
"userType": 0,
"flags": 8,
"type": {
"type": "INT4",
"name": "Int",
"id": 56
},
"colName": "TenantID"
}
}}
Next: (null)
Parent: {"tenantid": [
{
"value": 1,
"metadata": {
"userType": 0,
"flags": 8,
"type": {
"type": "INT4",
"name": "Int",
"id": 56
},
"colName": "TenantID"
}
}
]}
Path: "tenantid"
Previous: (null)
Static members:
Non-public members:
IEnumerator:
Root: {{
"name": "Rx Sidhu",
"given_name": "Rx",
"family_name": "Sidhu",
"locale": "en_US",
"emails": [
"ranxdeep#xxx.com",
"ranxdeep#xxx.com",
"ranxdeep#hx.com"
],
"nickname": "ranxdeep#xxx.com",
"email": "ranxdeep#xxx.com",
"picture": "https://apis.live.net/v5.0/f1xxxxxx/picture",
"roles": [
"Account Admin",
"Admin"
],
"tenantid": [
{
"value": 1,
"metadata": {
"userType": 0,
"flags": 8,
"type": {
"type": "INT4",
"name": "Int",
"id": 56
},
"colName": "TenantID"
}
}
],
"email_verified": true,
"clientID": "wxxxvC8",
"updated_at": "2015-07-15T16:26:30.526Z",
"user_id": "windowslive|f1axxxac",
"identities": [
{
"access_token": "EwBwAq1",
"provider": "windowslive",
"user_id": "f1aexxxxxac",
"connection": "windowslive",
"isSocial": true
}
],
"created_at": "2015-07-01T06:08:21.358Z"
}}
Type: 2
I need to check if the tenantID actually exists and then get value, else return null or 0.
You should be able to do:
JObject jObject = JObject.Parse(...);
JToken value = jObject.SelectToken("value");
You parse your object, then the inner contents should be exposed in which you can leverage the SelectToken method to find that specific value.
To build it out a bit, you could potentially do:
public static JToken FindToken<T>(string key, T value)
{
string serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
var jObject = JObject.Parse(serialized);
var jToken = jObject.SelectToken(key);
if(jToken != null)
return jToken;
return null;
}
I still cannot get the overall picture of your JSON, though have a look at this. It may help you.
var str = #"{
""x"": [{
""value"": 1,
""metadata"": {
""userType"": 0,
""flags"": 8,
""type"": {
""type"":""INT4"",
""name"":""Int"",
""id"": 56
},
""colName"":""TenantID""
}
}
]
}";
var parentJObject = JObject.Parse(str);
var xJArray = (JArray)parentJObject["x"];
// first item in JArray which is the object of interest
// look for the appropriate index of the JObject of your data
var firstJTokenInxJArray = (JObject)xJArray[0];
Console.WriteLine(firstJTokenInxJArray["value"].ToString());
I got what I was looking for :
JToken value;
if (usr.Profile.TryGetValue("tenantid", out value))
{
User.TenantID = (int)value [0] ["value"];
}

How to display JSON Data onto a UITableView

I am using Xamarin.iOS to return a JSON and attempt to place it on a UITableView, however I cannot seem to get it to work, here is what I am attempting to do so far:
Main View Controller
This is how I am returning the JSON
var request = new RestRequest {RootElement = "data", Resource = "/users/self/feed"};
request.AddParameter("access_token", instagramAccessToken);
var client = new RestClient ("https://api.instagram.com/v1");
// Edited Client Execution
client.ExecuteAsync(request, response =>
{
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(response.Content);
table.Source = new TableSource(rootObject.data);
table.ReloadData();
}
);
TableSource Class
public List<RootObject> Data { get; set; }
protected string cellIdentifier = "TableCell";
public TableSource ()
{
Data = new List<T> ();
}
public TableSource(List<T> data)
{
Data = data;
}
public override int RowsInSection (UITableView tableview, int section)
{
return Data.Count;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
if (OnRowSelected != null) {
OnRowSelected (this, new RowSelectedEventArgs (tableView, indexPath));
}
}
public class RowSelectedEventArgs : EventArgs
{
public UITableView tableView { get; set; }
public NSIndexPath indexPath { get; set; }
public RowSelectedEventArgs(UITableView tableView, NSIndexPath indexPath) : base()
{
this.tableView = tableView;
this.indexPath = indexPath;
}
}
public event EventHandler<RowSelectedEventArgs> OnRowSelected;
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier);
// if there are no cells to reuse, create a new one
if (cell == null)
cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier);
// Edited Text
cell.TextLabel.Text = ((Datum)Data[indexPath.Row]).user.username;
return cell;
}
I didn't really have a concrete method of displaying the JSON on the Table, so I would be pretty open to radical change. BTW the JSON loads on the MainViewController perfectly.
JSON Response
Most of your suggestions don't take into consideration how the JSON looks like so here you go:
{
"pagination": {
"next_url": "https://api.instagram.com/v1/users/self/feed?access_token=6489401.88b3fb2.7af2a0355ea24f4590efa1ee82ed0a49&max_id=668439962408115415_16915182",
"next_max_id": "668439962408115415_16915182"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"selfie"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "1393953134",
"link": "http://instagram.com/p/lIO1_jmkkr/",
"likes": {
"count": 14,
"data": [
{
"username": "muahjay",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_304620904_75sq_1392618687.jpg",
"id": "304620904",
"full_name": "Jeanettee Nicole Cambero Gamez"
},
{
"username": "iam_mrsmith31",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_32806209_75sq_1392607367.jpg",
"id": "32806209",
"full_name": "Kiondrix Smith"
},
{
"username": "anniyalation",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_30752906_75sq_1390523572.jpg",
"id": "30752906",
"full_name": "Niya G."
},
{
"username": "fonzo_badmon",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_271402803_75sq_1393641486.jpg",
"id": "271402803",
"full_name": "Slimshady"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage11.s3.amazonaws.com/e02592b0a3bf11e3b63212d269f676eb_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage11.s3.amazonaws.com/e02592b0a3bf11e3b63212d269f676eb_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage11.s3.amazonaws.com/e02592b0a3bf11e3b63212d269f676eb_8.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1393953134",
"text": "#Selfie",
"from": {
"username": "kthompkins7",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_5941681_75sq_1378508674.jpg",
"id": "5941681",
"full_name": "kthompkins7"
},
"id": "668849828018145517"
},
"user_has_liked": false,
"id": "668849827690989867_5941681",
"user": {
"username": "kthompkins7",
"website": "",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_5941681_75sq_1378508674.jpg",
"full_name": "kthompkins7",
"bio": "",
"id": "5941681"
}
},
{
"attribution": null,
"tags": [
"rp",
"amen"
],
"type": "image",
"location": null,
"comments": {
"count": 5,
"data": [
{
"created_time": "1393949795",
"text": "#tmcmc Dobson a Christian!!!!",
"from": {
"username": "keelanwillison",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_26089241_75sq_1380511035.jpg",
"id": "26089241",
"full_name": "Keelanwillison"
},
"id": "668821819276579152"
},
{
"created_time": "1393950029",
"text": "Yo my cousin got me a singed autograph from you at the Boston boat show thanks man #a_dobson3",
"from": {
"username": "danthebigboy914",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_27354625_75sq_1393859632.jpg",
"id": "27354625",
"full_name": "Danny Chiappetta"
},
"id": "668823778033324461"
},
{
"created_time": "1393950659",
"text": "Amen",
"from": {
"username": "sandyrodr",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_44889389_75sq_1361591427.jpg",
"id": "44889389",
"full_name": "sandyrodr"
},
"id": "668829062428545715"
},
{
"created_time": "1393950664",
"text": "🙏",
"from": {
"username": "cherydaily",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_18483862_75sq_1379884114.jpg",
"id": "18483862",
"full_name": "Andrew \"Drew\" Chery"
},
"id": "668829109488636596"
},
{
"created_time": "1393951921",
"text": "Amen",
"from": {
"username": "bostonsonia",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_182219303_75sq_1391293289.jpg",
"id": "182219303",
"full_name": "Sonia"
},
"id": "668839648625348773"
}
]
},
"filter": "Normal",
"created_time": "1393949714",
"link": "http://instagram.com/p/lIIUdggtOj/",
"likes": {
"count": 324,
"data": [
{
"username": "bwest05",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_387702554_75sq_1393739891.jpg",
"id": "387702554",
"full_name": "💥bb💥"
},
{
"username": "babygirl6193",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_23365060_75sq_1384972330.jpg",
"id": "23365060",
"full_name": "babygirl6193"
},
{
"username": "derekmooney1",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_218356294_75sq_1388601101.jpg",
"id": "218356294",
"full_name": "Derek Mooney"
},
{
"username": "zay0613",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_342812999_75sq_1369576584.jpg",
"id": "342812999",
"full_name": "Zay"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage11.s3.amazonaws.com/0e1b270aa3b811e395af12cdc849cb9b_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage11.s3.amazonaws.com/0e1b270aa3b811e395af12cdc849cb9b_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage11.s3.amazonaws.com/0e1b270aa3b811e395af12cdc849cb9b_8.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1393949714",
"text": "#RP from #flashgoodwin #AMEN",
"from": {
"username": "a_dobson3",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_203045179_75sq_1374262647.jpg",
"id": "203045179",
"full_name": "a_dobson3"
},
"id": "668821135462420769"
},
"user_has_liked": false,
"id": "668821135110099875_203045179",
"user": {
"username": "a_dobson3",
"website": "",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_203045179_75sq_1374262647.jpg",
"full_name": "a_dobson3",
"bio": "",
"id": "203045179"
}
},
{
"attribution": null,
"tags": [
"tb12"
],
"type": "image",
"location": null,
"comments": {
"count": 169,
"data": [
{
"created_time": "1393952642",
"text": "My guy! The greatest! I just want him to get another ring so the haters can stop saying he hasn't won one since 04. I mean he still won them right? #TomBrady #patriots",
"from": {
"username": "k_aus32",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_39840771_75sq_1390431094.jpg",
"id": "39840771",
"full_name": "k_aus32"
},
"id": "668845703585318559"
},
{
"created_time": "1393952673",
"text": "#heres_jonni9",
"from": {
"username": "allyson21lautner",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_184895764_75sq_1393107648.jpg",
"id": "184895764",
"full_name": "Allyson 💌"
},
"id": "668845962264823470"
},
{
"created_time": "1393952694",
"text": "Let's go !",
"from": {
"username": "tom12terrific",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_421023272_75sq_1393644166.jpg",
"id": "421023272",
"full_name": "Andrew Estrada"
},
"id": "668846135581853361"
},
{
"created_time": "1393952856",
"text": "♡",
"from": {
"username": "in_neverland74",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_181245582_75sq_1391928288.jpg",
"id": "181245582",
"full_name": "Karen💕"
},
"id": "668847491935880949"
},
{
"created_time": "1393952914",
"text": "Follow for patriots pics daily!! (Ifollowback)",
"from": {
"username": "ne_patriots_fanpage__",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_983242248_75sq_1391989748.jpg",
"id": "983242248",
"full_name": "New England Patriots Fanpage"
},
"id": "668847980295472912"
},
{
"created_time": "1393952952",
"text": "Best ever; period. Let's see anyone win a ring with the humps he's had to work with, (except Randy).",
"from": {
"username": "calidoso76",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_1101426299_75sq_1392654362.jpg",
"id": "1101426299",
"full_name": "calidoso76"
},
"id": "668848301545604900"
},
{
"created_time": "1393953005",
"text": "Shit just because brady hasn't won a ring since 04 don't mean a thing....one more and he'll have 6.....the most superbowl wins than ANY quarterback EVER. #patriots",
"from": {
"username": "inkandartsosick",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_260242163_75sq_1363337609.jpg",
"id": "260242163",
"full_name": "Eric Hughes"
},
"id": "668848744304723771"
},
{
"created_time": "1393953023",
"text": "👈🏈🙌",
"from": {
"username": "bvsed_papi_",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_408657565_75sq_1393905141.jpg",
"id": "408657565",
"full_name": "Abel Valle™"
},
"id": "668848894913791811"
}
]
},
"filter": "Lo-fi",
"created_time": "1393949267",
"link": "http://instagram.com/p/lIHd-_v8Uj/",
"likes": {
"count": 13685,
"data": [
{
"username": "dollathebarber",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_219503241_75sq_1373905843.jpg",
"id": "219503241",
"full_name": "dollathebarber"
},
{
"username": "emastro23",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_21122956_75sq_1388823730.jpg",
"id": "21122956",
"full_name": "Eddie Mastrocola"
},
{
"username": "pat_fan99",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_304601453_75sq_1377084414.jpg",
"id": "304601453",
"full_name": "Timothy Smith"
},
{
"username": "___adam___q",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_3694047_75sq_1367384028.jpg",
"id": "3694047",
"full_name": "Adam Quinonez"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage10.s3.amazonaws.com/1c67f514a3b711e383121299eef1f922_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage10.s3.amazonaws.com/1c67f514a3b711e383121299eef1f922_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage10.s3.amazonaws.com/1c67f514a3b711e383121299eef1f922_8.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1393949267",
"text": "#tb12",
"from": {
"username": "patriots",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_1939080_75sq_1385924433.jpg",
"id": "1939080",
"full_name": "New England Patriots"
},
"id": "668817391815214218"
},
"user_has_liked": false,
"id": "668817391496447267_1939080",
"user": {
"username": "patriots",
"website": "",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_1939080_75sq_1385924433.jpg",
"full_name": "New England Patriots",
"bio": "",
"id": "1939080"
}
},
{
"attribution": null,
"videos": {
"low_resolution": {
"url": "http://distilleryimage4.s3.amazonaws.com/2cb7114aa3b511e3a3e312f545262070_102.mp4",
"width": 480,
"height": 480
},
"standard_resolution": {
"url": "http://distilleryimage4.s3.amazonaws.com/2cb7114aa3b511e3a3e312f545262070_101.mp4",
"width": 640,
"height": 640
}
}
}
]
}
After those two Edits I still have two errors:
Error on Main View Controller
Error on Table Source
No need to assign the Data multiple times. Assign the source once and then call ReloadData().
client.ExecuteAsync(request, response =>
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(response.Content);
table.InvokeOnMainThread(() =>
{
table.Source = new TableSource(rootObject.data);
table.ReloadData();
});
}
);
EDIT: It seems there are four items in the Datum field and the last one is null.
https://github.com/sami1971/SimplyMobile/blob/master/iOS/Samples/TwitterSample/Twitter.cs
ToString() override for Datum:
public override string ToString()
{
if (user == null)
{
return "User is null";
}
return user.full_name;
}
For full sample download the project, open iOS/SimplyMobile.iOS.sln and run Samples/TwitterSample.
You should be able to do something like this:
cell.TextLabel.Text = ((Datum)Data[indexPath.Row]).user.username;
you have to reload tableView when all data retrived from url to your dictionary or array.
you can do this like this
[self.Yourtableview reloadData];

Categories