how to split the json value using c# - c#

I am having a JSON file like this:
"{\"page\":1,\"limit\":10,\"pages\":1,\"total_results\":2,\"districts\":[{\"object\":\"district\",\"links\":[],\"id\":\"3650117d-e60e-4b1d-897e-df5d6728a6a6\",\"name\":\"Wake County Public School System\",\"database_code\":\"NC183\",\"database_host\":\"osp-tdb01\",\"website\":\"WakeNC\",\"prefix\":\"00183\",\"state\":\"NC\",\"state_fips\":\"00\",\"county_code\":\"183\",\"short_county_code\":null,\"salesforce_id\":null,\"nces_id\":null,\"fee_per_transaction_credit\":0.0,\"fee_per_transaction_e_check\":0.0,\"fee_percent_credit\":0.04,\"fee_percent_e_check\":0.0,\"fee_paid_by\":null},{\"object\":\"district\",\"links\":[],\"id\":\"00000000-0000-0000-0000-000000000000\",\"name\":\"\",\"database_code\":\"NC183\",\"database_host\":\"OSP-DB01\",\"website\":\"WakeNC\",\"prefix\":\"37183\",\"state\":\"NC\",\"state_fips\":\"37\",\"county_code\":\"183\",\"short_county_code\":null,\"salesforce_id\":null,\"nces_id\":null,\"fee_per_transaction_credit\":0.0,\"fee_per_transaction_e_check\":0.0,\"fee_percent_credit\":0.0,\"fee_percent_e_check\":0.0,\"fee_paid_by\":null}]}"
here how to split the district - > id which has value "3650117d-e60e-4b1d-897e-df5d6728a6a6"
thanks..

You can parse it using Newtonsoft from Nuget. ie:
void Main()
{
var myJSON = JsonConvert.DeserializeAnonymousType(json, new { districts = new[] { new { id = Guid.NewGuid() }}});
foreach (var x in myJSON.districts)
{
Console.WriteLine(x.id);
}
}
static readonly string json = #"{
""page"": 1,
""limit"": 10,
""pages"": 1,
""total_results"": 2,
""districts"": [
{
""object"": ""district"",
""links"": [],
""id"": ""3650117d-e60e-4b1d-897e-df5d6728a6a6"",
""name"": ""Wake County Public School System"",
""database_code"": ""NC183"",
""database_host"": ""osp-tdb01"",
""website"": ""WakeNC"",
""prefix"": ""00183"",
""state"": ""NC"",
""state_fips"": ""00"",
""county_code"": ""183"",
""short_county_code"": null,
""salesforce_id"": null,
""nces_id"": null,
""fee_per_transaction_credit"": 0.0,
""fee_per_transaction_e_check"": 0.0,
""fee_percent_credit"": 0.04,
""fee_percent_e_check"": 0.0,
""fee_paid_by"": null
},
{
""object"": ""district"",
""links"": [],
""id"": ""00000000-0000-0000-0000-000000000000"",
""name"": """",
""database_code"": ""NC183"",
""database_host"": ""OSP-DB01"",
""website"": ""WakeNC"",
""prefix"": ""37183"",
""state"": ""NC"",
""state_fips"": ""37"",
""county_code"": ""183"",
""short_county_code"": null,
""salesforce_id"": null,
""nces_id"": null,
""fee_per_transaction_credit"": 0.0,
""fee_per_transaction_e_check"": 0.0,
""fee_percent_credit"": 0.0,
""fee_percent_e_check"": 0.0,
""fee_paid_by"": null
}
]
}";
Output:
3650117d-e60e-4b1d-897e-df5d6728a6a6
00000000-0000-0000-0000-000000000000

Related

NEST Elastic search empty values in Documents result

Elastic search noob question.
After reading some questions on SO I figured out to POST some data to my Index but I'm having some trouble getting back results.
I'm getting one document (as expected) but all properties are empty. The number of bytes 740 match the number of bytes received in Postman. I suspect the data isn't mapped right somehow..
Code:
var client = CreateCloudClient();
var indexName = "index-b";
var mustClauses = new List<QueryContainer>();
mustClauses.Add(new WildcardQuery
{
Field = new Field("FirstName"),
Value = "*ralf*"
});
var searchRequest = new SearchRequest<ProfileEntity>(indexName)
{
Query = new BoolQuery { Must = mustClauses }
};
var searchResponse = await client.SearchAsync<ProfileEntity>(searchRequest);
if (searchResponse.Hits.Any())
{
var person = searchResponse.Hits.First();
}
Debugger result
When using Postman:
GET ../westeurope.azure.elastic-cloud.com:9243/index-b/_search
{
"query": {
"bool": {
"must": [
{
"wildcard": {
"FirstName": "*ralf*"
}
}
]
}
}
}
I'm getting:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "index-b",
"_type": "_doc",
"_id": "0ec623e7-3837-4e83-808d-fed01398d1ab",
"_score": 1.0,
"_source": {
"Id": 0,
"ProfileId": "0ec623e7-3837-4e83-808d-fed01398d1ab",
"FirstName": "Ralf",
"LastName": "de K",
"BirthDate": "1999-09-19T00:00:00Z",
"BirthPlace": "Zwolle",
"BirthPlaceLocation": {
"Longitude": 41.9074,
"Latitude": -78.7911
},
"City": "Zwolle",
"Email": "email#example.org",
"ObjectIdentifier": "0ec623e7-3837-4e83-808d-fed01398d1ab",
"MobileNumber": "06123123123",
"Height": 2,
"BodyBuild": 0,
"Ethnicity": 8,
"Education": 3,
"Gender": 2,
"Created": "0001-01-01T00:00:00",
"Updated": "0001-01-01T00:00:00"
}
}
]
}
}
It was my own mistake. I used ElasticLowLevelClient to add a new index and I (probably) should have used ElasticClient because the first adds the index with pascal casing and the latter camel casing. Could be a config/setting but usinf ElasticClient fixes my problem.

C# Json LinQ - Build Json String Using Loop

I am trying to produce a Json string that looks like this:
{
"fromAddress": {
"streetLines": [
"100 Test St",
"Ste 100"
],
"city": "Orlando",
"stateOrProvinceCode": "FL",
"postalCode": "32819",
"countryCode": "US"
},
"toAddress": {
"streetLines": [
"101 Test St",
null
],
"city": "Orlando",
"stateOrProvinceCode": "FL",
"postalCode": "32819",
"countryCode": "US"
},
"packageDimensions": [
{
"weight": 20.0,
"length": "18",
"width": "12",
"height": "13"
},
{
"weight": 20.0,
"length": "18",
"width": "12",
"height": "13"
},
{
"weight": 20.0,
"length": "18",
"width": "12",
"height": "13"
}
]
}
I've gotten this far with my code:
var json = new
{
fromAddress = new
{
streetLines = new[]
{
fromAddress1,
fromAddress2
},
city = fromCity,
stateOrProvinceCode = fromState,
postalCode = fromZip,
countryCode = fromCountry
},
toAddress = new
{
streetLines = new[]
{
toAddress1,
toAddress2
},
city = toCity,
stateOrProvinceCode = toState,
postalCode = toZip,
countryCode = toCountry
},
};
That produces the following, which is lacking the pack dimensions:
{
"fromAddress": {
"streetLines": [
"100 Test St",
"Ste 100"
],
"city": "Orlando",
"stateOrProvinceCode": "FL",
"postalCode": "32819",
"countryCode": "US"
},
"toAddress": {
"streetLines": [
"101 Test St",
null
],
"city": "Orlando",
"stateOrProvinceCode": "FL",
"postalCode": "32819",
"countryCode": "US"
}
}
My data for the pack dimensions are stored thusly:
List<double> weight
string length
string width
string height
Multiple values for weight are passed in with the List, the dimensions are constants.
I need to find a way to add the pack dimensions, iterating through the weight List to do so. But I'm not sure how to approach it, adding a loop in the Json build doesn't work in any way.
I would appreciate any advice on getting the data iteration that I need. Thanks.
You have to add LINQ expression with projection:
var json = new
{
fromAddress = new
{
streetLines = new[]
{
fromAddress1,
fromAddress2
},
city = fromCity,
stateOrProvinceCode = fromState,
postalCode = fromZip,
countryCode = fromCountry
},
toAddress = new
{
streetLines = new[]
{
toAddress1,
toAddress2
},
city = toCity,
stateOrProvinceCode = toState,
postalCode = toZip,
countryCode = toCountry
},
packageDimensions = weight.Select(w => new
{
weight = w,
length = length,
width = width,
height = height
})
.ToArray()
};

The remote server returned an error: (415) Unsupported Media Type in uploadString method

I am calling API with "PUT" Method using Web Client in C# Code,When I run this source code it shows an error message as "The remote server returned an error: (415) Unsupported Media Type" in uploadString method".
Please check below source code with Json data and advise how to resolve this error.
Note:-
Where "DATA" in source code is Json Data
Source Code:-
using (var client = new WebClient())
{
client.Headers.Add("owner_id", "78c6beda-54a2-11ea-b064-0af3f8b02c24");
client.Headers.Add("gstin", "29AAFCD5862R000");
string url = "https://einvoicing.internal.cleartax.co/v2/eInvoice/generate";
string res = client.UploadString(url, "PUT", DATA);
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<YourClass>(res);
}
Json Data :-
[
{
"transaction": {
"Version": "1.01",
"TranDtls": {
"TaxSch": "GST",
"SupTyp": "EXPWOP",
"RegRev": "N",
"EcmGstin": null,
"IgstOnIntra": null
},
"DocDtls": {
"Typ": "INV",
"No": "G/E/20-21/0175",
"Dt": "11/09/2020"
},
"SellerDtls": {
"Gstin": "29AAFCD5862R000",
"LglNm": "K.H Exports India Private Limited",
"TrdNm": "K.H Exports India Private Limited (Glove Division)",
"Addr1": "142/,Trunk Road",
"Addr2": "Perumugai",
"Loc": "Via Vellore",
"Pin": "560037",
"Stcd": "29",
"Ph": "04162253164",
"Em": "edp.kharind#khindia.com"
},
"BuyerDtls": {
"Gstin": "URP",
"LglNm": "H M FINANCE AB",
"TrdNm": "H M FINANCE AB",
"Pos": "96",
"Addr1": "MASTER SAMUELSGATAN 46 A, 106 38 STOCKHOLM SWEDEN ",
"Addr2": null,
"Loc": "Sweden",
"Pin": "999999",
"Stcd": "96",
"Ph": null,
"Em": null
},
"DispDtls": null,
"ShipDtls": {
"Gstin": "URP",
"LglNm": "LOGIX FZCO",
"TrdNm": "LOGIX FZCO",
"Addr1": "PO BOX 261422 PLOT NO. S21515, SOUTH BLOCK JEBEL ALI FREE ZONE DUBAI UNITED ARAB EMIRATES ",
"Addr2": null,
"Loc": "United Arab Emirates",
"Pin": "999999",
"Stcd": "96"
},
"ItemList": [
{
"SlNo": "0001",
"PrdDesc": "FINE LEATHER GLOVES MADE OUT OF SHEEP LEATHER FOR LADIES. ",
"IsServc": "N",
"HsnCd": "42032920",
"Barcde": null,
"Qty": 10.0,
"FreeQty": 0.0,
"Unit": "PR",
"UnitPrice": 452.50,
"TotAmt": 4525.00,
"Discount": 0.0,
"PreTaxVal": 4525.00,
"AssAmt": 4525.00,
"GstRt": 0.0,
"IgstAmt": 0.0,
"CgstAmt": 0.0,
"SgstAmt": 0.0,
"CesRt": 0.0,
"CesAmt": 0.0,
"CesNonAdvlAmt": 0.0,
"StateCesRt": 0.0,
"StateCesAmt": 0.0,
"StateCesNonAdvlAmt": 0.0,
"OthChrg": 0.0,
"TotItemVal": 4525.00,
"OrdLineRef": null,
"OrgCntry": null,
"PrdSlNo": null,
"BchDtls": null,
"AttribDtls": null
}
],
"ValDtls": {
"AssVal": 4525.00,
"CgstVal": 0.0,
"SgstVal": 0.0,
"IgstVal": 0.0,
"CesVal": 0.0,
"StCesVal": 0.0,
"Discount": 0.0,
"OthChrg": 0.0,
"RndOffAmt": 0.0,
"TotInvVal": 4525.00,
"TotInvValFc": 0.0
}
]

Trouble obtaining object values within an array using C#

I am using C# and unable to obtain JSON data values for the JSON below:
I am trying to obtain all name value pairs for:
body.quotes.vehicle.key
and
body.quotes.prices.pricing-fixed.price
The JSON contains several of these 'vehicle' and 'prices' objects (repeated for different vehicle types) although I've only included one below to keep the code succinct.
I can see that "quotes" is an array containing multiple vehicle and pricing objects but I'm stuck on the fact that each of the containing objects doesn't seem to have a direct name value pair so I can't work out how to obtain the values I need.
{
"version": 243,
"code": "0",
"body": {
"quotes": [
{
"vehicle": {
"id": null,
"title": "Any Vehicle",
"key": "R4",
"description": "4 Seater",
"group": "NOMAP"
},
"prices": {
"pricing-fixed": {
"id": "18277",
"title": "FIXED",
"type": "fixedfare",
"alt": false,
"cost": 25,
"price": 25,
"tip": 0,
"commission": 0.5,
"auto": "1",
"priority": 1,
"schedulable": "1",
"for_account": false,
"audit": {
"zonecharges": []
},
"attributeextras_cost": 0,
"attributeextras_price": 0,
"round_robin": 0,
"waitAndReturn": false,
"prebooking_extra_price": "0.00",
"waitAndReturnCostDiscount": 0,
"waitAndReturnPriceDiscount": 0
}
}
},
{
"vehicle": { ...//etc.
I have tried the following C# code but (string)iCabbiVehicleJson["vehicle.key"] is null. (I believe this line is the problem?)
Code snippet:
string jsonResponseAsString = returnJson.ToString();
JObject iCabbiResponseJson = JObject.Parse(jsonResponseAsString);
List<iCabbiQuoteVehicleFare> vehicleFares = new List<iCabbiQuoteVehicleFare>();
foreach (JToken vehicleFare in iCabbiResponseJson.SelectToken("body.quotes"))
{
try
{
JObject iCabbiVehicleJson = JObject.Parse(vehicleFare.ToString());
string vehicleKey = (string)iCabbiVehicleJson["vehicle.key"];
decimal fare = (decimal)iCabbiVehicleJson["prices.pricing-fixed.price"];
vehicleFares.Add(new iCabbiQuoteVehicleFare
{
VehicleKey = vehicleKey,
Fare = fare
});
}
catch (Exception ex)
{
string errorMessage = ex.Message;
}
}
the variable vehicleFares actually returns the below. That double curly braces is most likely the issue...
{{
"vehicle": {
"id": null,
"title": "Any Vehicle",
"key": "R4",
"description": "4 Seater",
"group": "NOMAP"
},
"prices": {
"pricing-fixed": {
"id": "18277",
"title": "FIXED",
"type": "fixedfare",
"alt": false,
"cost": 25,
"price": 25,
Thanks.
The problem is the square bracket indexer syntax of JToken does not support dotted property paths. You need to use the SelectToken() method for that.
Change these lines:
string vehicleKey = (string)iCabbiVehicleJson["vehicle.key"];
decimal fare = (decimal)iCabbiVehicleJson["prices.pricing-fixed.price"];
to this:
string vehicleKey = (string)iCabbiVehicleJson.SelectToken("vehicle.key");
decimal fare = (decimal)iCabbiVehicleJson.SelectToken("prices.pricing-fixed.price");
Fiddle: https://dotnetfiddle.net/nkSu5y
I think you can just treat them as dynamic and iterate over them using a for loop. I just did something like this using your example data, and it seemed to work.
Fiddle
// Where the data variable holds your json string
var json = JsonConvert.DeserializeObject<dynamic>(data);
var count = json.body.quotes.Count;
for(var i = 0; i < count; i++) {
Console.WriteLine(json.body.quotes[i].vehicle.key);
Console.WriteLine(json.body.quotes[i].prices["pricing-fixed"]);
}

Iterating through a nested JSON Array in C# with Newtonsoft

I have a block of JSON as follows:
[
{
"id": 1,
"name": "Section1",
"project_id": 100,
"configs": [
{
"id": 1000,
"name": "myItem1",
"group_id": 1
}
]
},
{
"id": 2,
"name": "Section2",
"project_id": 100,
"configs": [
{
"id": 1001,
"name": "myItem2",
"group_id": 2
},
{
"id": 1002,
"name": "myItem3",
"group_id": 2
},
{
"id": 1003,
"name": "myItem4",
"group_id": 2
}
]
},
{
"id": 3,
"name": "Section3",
"project_id": 100,
"configs": [
{
"id": 1004,
"name": "myItem5",
"group_id": 5
},
]
}
]
I have pulled it into Memory as a JArray.
I need to iterate through this such that I'm grabbing a list of ids and name from only the config sub-arrays. Ideally, I'll end up with something like this:
1000, myItem1
1001, myItem2
1002, myItem3
1003, myItem4
1004, myItem5
I'm having a hard time understanding what Newstonsoft calls a JObject vs a JArray, or how to access the various parts of each of those data structures. What I have right now is as follows:
foreach (JObject config in result["configs"])
{
string id = (string)config["id"];
string name = (string)config["name"];
string gid = (string)config["group_id"];
Console.WriteLine(name + " - " + id + " - " + gid);
}
This does not work, but I hope it illustrates what my end goal is. I've been unable to piece together how to accomplish this goal.
A JObject is an object (analogous to a class):
{
"a": 1,
"b": true
}
A JArray is a JSON array, and contains multiple JObject entities:
[
{
"a": 1,
"b": true
},
{
"a": 2,
"b": true
}
]
The root of a JSON document can be an object, or an array. In your case, it's an array.
The following code and fiddle reveals that your code is fine, provided that you deserialize the document as what it is - an array.
string json = "[{\"id\":1,\"name\":\"Section1\",\"project_id\":100,\"configs\":[{\"id\":1000,\"name\":\"myItem1\",\"group_id\":1}]},{\"id\":2,\"name\":\"Section2\",\"project_id\":100,\"configs\":[{\"id\":1001,\"name\":\"myItem2\",\"group_id\":2},{\"id\":1002,\"name\":\"myItem3\",\"group_id\":2},{\"id\":1003,\"name\":\"myItem4\",\"group_id\":2}]},{\"id\":3,\"name\":\"Section3\",\"project_id\":100,\"configs\":[{\"id\":1004,\"name\":\"myItem5\",\"group_id\":5},]}]";
JArray obj = Newtonsoft.Json.JsonConvert.DeserializeObject<JArray>(json);
foreach (var result in obj)
{
foreach (JObject config in result["configs"])
{
string id = (string)config["id"];
string name = (string)config["name"];
string gid = (string)config["group_id"];
Console.WriteLine(name + " - " + id + " - " + gid);
}
}

Categories