I am using netownsoft json.net to serlize an object but its adding string at the start I dont under stand why its doing this.
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
public async Task<T> GetDataFromSageService<T>(string url, params string[] args)
where T : class
{
var uri = new Uri(string.Format(url, args));
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
}
return default(T);
}
I am using the following to encode my end point which is hosted in a wcf service.
public string GetWarehouses()
{
DataSet ds = new SqlDa().GetWarehouses();
ds.Tables[0].TableName = "Warehouses";
return JsonConvert.SerializeObject(ds, Formatting.Indented);
}
But the string i am getting back is as such
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{
"Warehouses": [
{
"WarehouseID": 13016489,
"Name": "B",
"Description": "Belfast "
},
{
"WarehouseID": 13016647,
"Name": "B",
"Description": "B"
},
{
"WarehouseID": 13815467,
"Name": "Direct Delivery",
"Description": ""
},
{
"WarehouseID": 1008,
"Name": "PW",
"Description": "Postal Way"
},
{
"WarehouseID": 13016234,
"Name": "H",
"Description": "Hospital"
},
{
"WarehouseID": 13016238,
"Name": "MPC",
"Description": "Clinic"
},
{
"WarehouseID": 13029366,
"Name": "O",
"Description": "Outpatient"
},
{
"WarehouseID": 13815466,
"Name": "Returns",
"Description": ""
}
]
}
</string>
As You can see its enclosed it as a string for some reason and don't understand as to why. Is their a way with the data set to make sure that it gets converted into proper json.
If you don't want to modify your server code, you could use regex to extract legal json string from your response.
string content ="your context with xml"
Regex regex = new Regex("<string\\s*xmlns=\".*\">([\\s\\S]*)</string>");
Match match = regex.Match(content);
Response.Write(match.Groups[1].Value);
Newtonsoft.Json.JsonConvert.DeserializeObject(match.Groups[1].Value);
Related
I am working with an API that uses GraphQL and returns JSON data and I want to deserialize the JSON content dynamically rather than map the entire service structure in my application into C# data structures (.NET types/classes).
I've done this before but the JSON data was quite simple and straightforward. However, the this API I'm working with returns more complex/verbose JSON and I'm struggling to parse it properly.
Can anyone advise on how to parse the below JSON? That is, how to access the dynamic JSON's objects/properties.
I'm using Newtonsoft.Json. This is my code to deserialize:
byte bC = 0;
string location_text = string.Empty;
string location_value = string.Empty;
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);
foreach (dynamic d in results)
{
bC = d.data.locationSuggestions.Count; // d.locationSuggestions.Count
for (byte b = 0; b < bC; b++)
{
location_text = d.data.locationSuggestions[b].location.contextualName;
location_value = d.data.locationSuggestions[b].location.id.value;
}
}
When I run this code I get an error that says "data" or "locationSuggestions" cannot be found.
The JSON I'm trying to parse is as follows:
{
"data": {
"locationSuggestions": [
{
"location": {
"id": {
"value": "seekAnzPublicTest:location:seek:2dkY4vZJF"
},
"name": "Brisbane",
"contextualName": "Brisbane QLD 4000 AU",
"countryCode": "AU",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:2FjxhQans"
},
"name": "CBD & Inner Suburbs",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:32XZdsa2K"
},
"name": "Brisbane"
}
}
}
},
{
"location": {
"id": {
"value": "seekAnzPublicTest:location:seek:2ckmimaF1"
},
"name": "Brisbane Grove",
"contextualName": "Brisbane Grove NSW 2580 AU",
"countryCode": "AU",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:2UC23LszP"
},
"name": "Southern Highlands & Tablelands",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:FTwZdE2K"
},
"name": "New South Wales"
}
}
}
}
]
},
"extensions": {
"requestLatency": 171
}
}
Regarding your JSON string, you can use dynamic to parse it and access the data as shown below:
You can also find a working example at: https://dotnetfiddle.net/lnhwJz
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var jsonString=#"{'data':{'locationSuggestions':[{'location':{'id':{'value':'seekAnzPublicTest:location:seek:2dkY4vZJF'},'name':'Brisbane','contextualName':'Brisbane QLD 4000 AU','countryCode':'AU','parent':{'id':{'value':'seekAnzPublicTest:location:seek:2FjxhQans'},'name':'CBD & Inner Suburbs','parent':{'id':{'value':'seekAnzPublicTest:location:seek:32XZdsa2K'},'name':'Brisbane'}}}},{'location':{'id':{'value':'seekAnzPublicTest:location:seek:2ckmimaF1'},'name':'Brisbane Grove','contextualName':'Brisbane Grove NSW 2580 AU','countryCode':'AU','parent':{'id':{'value':'seekAnzPublicTest:location:seek:2UC23LszP'},'name':'Southern Highlands & Tablelands','parent':{'id':{'value':'seekAnzPublicTest:location:seek:FTwZdE2K'},'name':'New South Wales'}}}}]},'extensions':{'requestLatency':171}}";
var parsedData=JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach(var item in parsedData.data.locationSuggestions)
{
Console.WriteLine(item.location.name);
Console.WriteLine(item.location.id.value);
Console.WriteLine(item.location.contextualName);
}
}
}
Output:
Brisbane
seekAnzPublicTest:location:seek:2dkY4vZJF
Brisbane QLD 4000 AU
Brisbane Grove
seekAnzPublicTest:location:seek:2ckmimaF1
Brisbane Grove NSW 2580 AU
Can you help me parse the values in 'realEstateProperties' attribute (ex. serial number and economyType.value). Here is a part of the json file:
{
"Entity1": {
"id": "5f514d20744a1fb",
"realEstateProperties": [
{
"serialNumber": "11",
"cadastralSections": [
{
"id": "5f514dc11a1e3",
"economyType": {
"value": "landRegisterPage.type",
}
}
],
"landRegisterPage": {
"id": "3456",
"landRegisterBook": {
"abbreviation": null
},
"note": "LRP",
"tags": null
},
"propertyTextBlock": null
}
],
"customFields": [],
Here is what I currently have:
public static string[] GetJsonValues(string jsonProperty)
{
testCaseName = "Entity1";
FixtureIncident.Root incObject = new FixtureIncident.Root();
incObject = LoadJSONFile();
JObject incJson = JObject.FromObject(incObject);
var attributes = incJson[testCaseName].ToList<JToken>();
var property = attributes.Find(i => i.ToObject<JProperty>().Name == jsonProperty) as JArray; //returns property=null
string[] Properties = property.ToObject<string[]>();
return Properties;
}
property returns null and I am not sure how to correct it.
I need to save all the realEstateProperties values in a string[].
I found some similar topics but I couldn't adjust my code so I make it works. Thanks in advance for your help.
i am inserting json format but need to know how i can insert in this format as mention below
{
"products": [
{
"product_id": "55",
"name": "testing data",
"price": "77",
"total": "77",
"quantity": "1",
"type": "kg"
}],
],
"totals": [
{
"code": "sub_total",
"title": "Sub-Total",
"text": "Rs277.00",
"value": "277.0000",
"sort_order": "1"
}]
}
here is my code which i am trying
items local = new items();
foreach (var item in _LocalItem){
local = new items
{
name = item.name
};
}
var json = JsonConvert.SerializeObject(local);
var request = new HttpRequestMessage(HttpMethod.Post, "http://orangepotato.rjcpacking.com/index.php?route=api/login/addcustomerOrder");
request.Content = new StringContent(json);
i dont understand where i can add "products" array in json format
Simply: don't serialize an array - serialize something that has an array in a member called products:
var json = JsonConvert.SerializeObject(new { products = local });
I am fetching /me/apprequests from Facebook API. It works and I get the data in JSON format.
Thing is that everything is nested, like a dictionary inside a dictionary.
What i tried:
Dictionary<string, object> dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as Dictionary<string, object>;
object data;
string request_code = "";
if (dict.TryGetValue("data", out data))
{
var rc = (((Dictionary<string, object>)data)["id"]);
request_code = (string)rc;
}
Debug.Log("request_code=" + request_code);
I think I need to loop the dictionary to get all id's.
I can confirm that if (dict.TryGetValue("data", out data)) does work correctly and get the dictionary of data arrays, but fails here (((Dictionary<string, object>)data)["id"]); with casting error.
Json looks like:
{
"data": [{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T16:01:15+0000",
"from": {
"name": "David boom",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "413880842521239_10156578101000000"
},
{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T14:12:41+0000",
"from": {
"name": "David boom2",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "316676422209302_10156578101000000"
}],
"paging": {
"cursors": {
"before": "NDEzODgwODQyNTIxMjM5Ojc1OTQzODY4NAZDZD",
"after": "MzE2Njc2NDIyMjA5MzAyOjc1OTQzODY4NAZDZD"
}
}
}
Managed to make it work if it will help someone:
string request_code = "";
if (dict.TryGetValue("data", out data))
{
int dataLength = ((List<object>)data).Count;
for (int i = 0; i < dataLength; i++)
{
var rc = ((List<object>)data)[i];
var rc2 = (((Dictionary<string, object>)rc)["id"]);
request_code = (string)rc2;
Debug.Log("request_code=" + request_code);
}
}
this is my json file
{
{
"#odata.context": "https://api.onedrive.com/v1.0/$metadata#drives('me')/items('root')/children/$entity",
"createdBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"createdDateTime": "2016-05-12T07:25:36.463Z",
"cTag": "adDo2MTFDMTlFQjAzOEQ1QUExITEyNC42MzU5ODYzODk5MTI3MDAwMDA",
"eTag": "aNjExQzE5RUIwMzhENUFBMSExMjQuMw",
"id": "611C19EB038D5AA1!124",
"lastModifiedBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z",
"name": "Nopbackup",
"parentReference": {
"driveId": "611c19eb038d5aa1",
"id": "611C19EB038D5AA1!105",
"path": "/drive/root:"
},
"size": 0,
"webUrl": "https://onedrive.live.com/redir?resid=611C19EB038D5AA1!124",
"fileSystemInfo": {
"createdDateTime": "2016-05-12T07:25:36.463Z",
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z"
},
"folder": {
"childCount": 0
}
}
}
i want to get this "id": "4c190e01" from json
dynamic value = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(value.id[0]);
this is my code but i am not getting 4c190e01 id
rewrite your code as following...
dynamic valuePoco = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(valuePoco.createdBy.application.id);
You can use the path to the desired property. If you want to select the element with 4c190e01 as id, you can use
string id = value.createdBy.application.id;
or
string id = value.lastModifiedBy.application.id;
depending on your needs.
As it was pointed out, you'd need to fix your JSON first and remove the first { and the last }
First thing first, Your json is invalid.
You've to remove one { from top and } from the bottom and then use the following code:
dynamic jsonObj = JsonConvert.DeserializeObject(result);
string id = jsonObj.createdBy.application.id.ToString();