Parsing JSON file C# - c#

I have the following JSON that I want to parse into C#. I am trying to avoid outside libraries but if I have to I can use them. Right now I am using the JavaScriptSerializer method of parsing from a JSON file following the answer on another stackoverflow question Unfortunately I can have any number of the objectX items under Resources and they all have different names. Is there another way of doing this?
{
"FormatVersion" : "2010-09-09",
"Description" : "My JSON Description",
"Parameters" : {
"Product" : {
"Description" : "Product name",
"Type" : "String",
"Default" : "cs42"
},
"DifferentObjectSize" : {
"Description" : "DifferentObjectSize",
"Type" : "String",
"Default" : "large"
},
"ObjectSize" : {
"Description" : "Worker size",
"Type" : "String",
"Default" : "medium"
}
},
"Resources" : {
"differentobject" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "DifferentObjectSize" }
}
},
"object1" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "ObjectSize" }
}
},
"object2" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "ObjectSize" }
}
},
"object3" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "ObjectSize" }
}
},
"object4" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "ObjectSize" }
}
},
}
}

If you think to use Json.Net you can parse your input string as below
JObject myObj = (JObject)JsonConvert.DeserializeObject(jsonString);
foreach(var resource in myObj["Resources"])
{
var props = resource.Children<JObject>().First();
Console.WriteLine(props["Type"] + " " + props["Properties"]["InstanceType"]["Ref"]);
}

Related

C# Retrieving a specific piece of information from JSON string by using Newtonsoft.json

JSON string that i retrieved:
{
"trackItemResponse" : {
"hdr" : {
"messageType" : "TRACKITEM",
"messageDateTime" : "2021-04-28T16:32:05+08:00",
"messageVersion" : "1.0",
"messageLanguage" : "en"
},
"bd" : {
"shipmentItems" : [ {
"masterShipmentID" : null,
"shipmentID" : "MYCGUMY8202104SIN00005",
"trackingID" : "5021049762931421",
"orderNumber" : null,
"handoverID" : null,
"shippingService" : {
"productCode" : "PDO",
"productName" : "Parcel Domestic"
},
"consigneeAddress" : {
"country" : "MY"
},
"weight" : "804",
"dimensionalWeight" : "640",
"weightUnit" : "G",
"events" : [ {
"status" : "77093",
"description" : "Successfully delivered",
"dateTime" : "2021-04-06 13:47:56",
"timezone" : "LT",
"address" : {
"city" : "Skudai",
"postCode" : "81300",
"state" : "JOHOR",
"country" : "MY"
}
}, {
"status" : "77090",
"description" : "Out for Delivery",
"dateTime" : "2021-04-06 10:51:55",
"timezone" : "LT",
"address" : {
"city" : "Skudai",
"postCode" : "81300",
"state" : "JOHOR",
"country" : "MY"
}
}, {
"status" : "77184",
"description" : "Processed at delivery facility",
"dateTime" : "2021-04-06 07:56:07",
"timezone" : "LT",
"address" : {
"city" : "Skudai",
"postCode" : "81300",
"state" : "Johor",
"country" : "MY"
}
}, {
"status" : "77178",
"description" : "Arrived at facility",
"dateTime" : "2021-04-06 07:30:26",
"timezone" : "LT",
"address" : {
"city" : "Skudai",
"postCode" : "81300",
"state" : "Johor",
"country" : "MY"
}
}, {
"status" : "77169",
"description" : "Departed from facility",
"dateTime" : "2021-04-06 05:22:02",
"timezone" : "LT",
"address" : {
"city" : "Kuala Lumpur Hub",
"postCode" : "47100",
"state" : "Kuala Lumpur",
"country" : "MY"
}
}, {
"status" : "77027",
"description" : "Sorted to delivery facility",
"dateTime" : "2021-04-05 21:00:05",
"timezone" : "LT",
"address" : {
"city" : "Kuala Lumpur Hub",
"postCode" : "47100",
"state" : "Kuala Lumpur",
"country" : "MY"
}
}, {
"status" : "77015",
"description" : "Processed at facility",
"dateTime" : "2021-04-05 20:59:04",
"timezone" : "LT",
"address" : {
"city" : "Kuala Lumpur Hub",
"postCode" : "47100",
"state" : "Kuala Lumpur",
"country" : "MY"
}
}, {
"status" : "71005",
"description" : "DATA SUBMITTED",
"dateTime" : "2021-04-02 15:44:40",
"timezone" : "Malaysia",
"address" : {
"city" : "SEPANG, SELANGOR",
"postCode" : "43900",
"state" : "SEL",
"country" : "MY"
}
} ]
} ],
"responseStatus" : {
"code" : "200",
"message" : "SUCCESS",
"messageDetails" : [ {
"messageDetail" : "1 tracking reference(s) tracked, 1 tracking reference(s) found."
} ]
}
}
}
}
Output that i wanted:
5021049762931421 //trackingID
Method_1 that i've tried:
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Console.WriteLine(result);
dynamic data = JObject.Parse(result);
Console.WriteLine(data.trackItemResponse.bd.shipmentItems.trackingID);
}
Output:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''Newtonsoft.Json.Linq.JArray' does not contain a definition for 'trackingID''
Method_2 that i've tried:
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var trckID = JObject.Parse(result)["trackItemResponse"]["bd"]["shipmentItems"].Select(x => (string)x["trackingID"]).ToList();
Console.WriteLine("Below is json data");
Console.WriteLine(trckID);
Console.WriteLine("Until here la");
}
Output_2:
Below is json data
System.Collections.Generic.List`1[System.String]
Until here la
Method_3 that i've tried:
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string jsonData = JObject.Parse(result)["trackItemResponse"]["bd"]["shipmentItems"]["trackingID"].ToString();
Console.WriteLine("Below is json data");
Console.WriteLine(jsonData);
Console.WriteLine("Until here la");
}
Output_3:
System.ArgumentException: 'Accessed JArray values with invalid key value: "trackingID". Int32 array index expected.'
Is there any other methods that could work? Thank you.
Post that i've refered
Convert string to int C#
C# cast from string to int/int32
Make newtonsoft.json convert default to int32 rather than int64
C# extract json array with newtonsoft.json
Thank you for your kind assistance!
You are looking for
var result = JObject.Parse(result)["trackItemResponse"]["bd"]["shipmentItems"][0]["trackingID"].ToString();
But keep in mind that shipmentItems is a list, so could contain multiple items.
This code only checks the first in that list.
SelectToken is what you are looking for:
var semiParsedJson = JObject.Parse(json);
var trackingId = semiParsedJson
.SelectToken("trackItemResponse.bd.shipmentItems[0].trackingID");
Please bear in mind that this solution assumes that the first object in the shipmentItems collection contains the required information.
If it is not present then trackingId will be null.
If you have multiple objects inside the shipmentItems and you are interested about all of the trackingId values then you have to use SelectTokens
var semiParsedJson = JObject.Parse(json);
var trackingIds = semiParsedJson
.SelectTokens("trackItemResponse.bd.shipmentItems[*].trackingID");
Please note that the indexer operator now receives a * wildcard.
From your code, you are almost there.
Since the object "data.trackItemResponse.bd.shipmentItems" is an array, you need to access the "trackingID" after selecting the index.
Your code should be:
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Console.WriteLine(result);
dynamic data = JObject.Parse(result);
//Test this
var trackingID = data.trackItemResponse.bd.shipmentItems[0].trackingID;
Console.WriteLine(data.trackItemResponse.bd.shipmentItems[0].trackingID);
}

C# Filter to get specific Mongo Document

{
"_id" : {
"order" : "0000006"
},
"Catgeory" : [
{
"ID" : "62982698",
"Data" : [
{
"NO" : "62982698",
"History" : [
{
"Status" : null,
}
]
}
]
},
{
"ID" : "63002696",
"Data" : []
}
],
"Info_ID" : [
"6000016405"
]
}
How to write c# mongo filter to get No:62982698 with "Info_ID" :"6000016405". No:62982698 can be part of multiple documents.So want to write filter that filters document with No 62982698 and "Info_ID" :"6000016405"

MongoWriteException: A write operation resulted in an error. The positional operator did not find the match needed from the query

I have a collection Zonedetails shown below. below.
I am using C# to Insert or Update a Unit to Units array. If it is an insert I can insert Area blank. If it is an update It should only update the UnitName.
{
"Code" : "Zone1",
"Name" : "ZoneName1",
"Units" : [
{
"UnitCode" : "Unitcode1",
"UnitName" : "UnitCodeName",
"Areas" : [
{
"AreaCode" : "AreaCode1",
"AreaName" : "AreaName1"
}
]
}
]
}
{
"Code" : "Zone2",
"Name" : "ZoneName2",
"Units" : [
{
"UnitCode" : "UnitCode2",
"UnitName" : "UnityName2",
"Areas" : [
{
"AreaCode" : "Areacode2",
"AreaName" : "AreaName2"
}
]
}
]
}
{
"Code" : "Zone3",
"Name" : "ZoneName3",
"Units" : [
{
"UnitCode" : "UnitCode3",
"UnitName" : "UnitName3",
"Areas" : [
{
"AreaCode" : "Areadcode3",
"AreaName" : "AreaName3"
},
{
"AreaCode" : "AreaCode4",
"AreaName" : "Areaname4"
},
{
"AreaCode" : "AreaCode5",
"AreaName" : "Areaname5"
}
]
},
{
"UnitCode" : "UnitCode6",
"UnitName" : "UnitName6",
"Areas" : [
{
"AreaCode" : "AreaCode10",
"AreaName" : "AreaName10"
},
{
"AreaCode" : "AreaCOde11",
"AreaName" : "AreaName10"
},
{
"AreaCode" : "AreaCode12",
"AreaName" : "AreaName12"
}
]
}
]
}
I have writtent a C# code shown below. But getting "The positional operator did not find the match needed from the query"error if the Unit Code does not exist. Added not before unitCode check.
var mongoCollection = _context.GetCollection<Zone>("ZoneDetail");
var filter = Builders<Zone>.Filter.Where(x => x.Code == zoneCode && !x.Units.Any(u => u.UnitCode == unit.UnitCode));
var updateUnitCode = Builders<Zone>.Update.Set(x => x.Units.ElementAt(-1).UnitCode, unit.UnitCode);
var updateUnitName = Builders<Zone>.Update.Set(x => x.Units.ElementAt(-1).UnitName, unit.UnitName);
var result = await mongoCollection.UpdateOneAsync(filter, Builders<Zone>.Update.Combine(updateUnitCode, updateUnitName), new UpdateOptions { IsUpsert = true});
Your error message suggest that filter is not able to find matching element.
Either try to change your input or change your filter criteria.

Elasticsearch not analyzed is missing on index

Every day I create the index on Elastic server which is hosted on AWS. Elastic Index format is abcnoteyyyyMMdd. You can look below the mapping result of Index.I am creating the index through ElasticSearch.Nest.
Index Creation Code:
DateTime _instance = DateTime.Now;
if (!(client.IndexExists("eccnote" + _instance.ToString("yyyyMMdd"))).Exists)
{
var createIndexResult = client.CreateIndex("eccnote" + _instance.ToString("yyyyMMdd"));
var mapResult = client.Map<ESNote>(c => c.MapFromAttributes().IgnoreConflicts().Type("esnote").Indices("eccnote" + _instance.ToString("yyyyMMdd")));
}
But there is some problem, I do not know what is it? An index is being created successfully. but someday I am getting "index" : "not_analyzed" is missing from mapping results. For example here is the mapping result of Index dated 20160615. Here the result is in a proper format.
GET **indexname20160615**/_mapping?pretty
output result:-
{
"indexname" : {
"mappings" : {
"type" : {
"properties" : {
"#timestamp" : {
"type" : "date",
"format" : "dateOptionalTime"
},
"account" : {
"type" : "string",
"index" : "not_analyzed"
},
"type" : {
"type" : "integer"
},
"userid" : {
"type" : "string",
"index" : "not_analyzed"
}
}
}
}
}
}
But when I see the mapping result of index dated 20160614,It is showing like this. Here "index" : "not_analyzed" properties is missing. It is happening for the random day only. I do not know why?
GET indexname20160614/_mapping?pretty
{
indexname20160614" : {
"mappings" : {
"indextype" : {
"properties" : {
"#timestamp" : {
"type" : "date",
"format" : "dateOptionalTime"
},
"session" : {
"type" : "string"
},
"tn" : {
"type" : "string"
},
"type" : {
"type" : "long"
},
"userid" : {
"type" : "string"
}
}
}
}
}
}
Why is it happening? Because every day through C# code, we create the index on ElasticServer but sometimes it is in proper format, sometimes it is not.

MongoDb Query Array on C#

Im dba and development a C# Web App to get information from Mongodb, but when i try to get information from an array attribute, the C# show me all element of the document that contain the element that i find. I just want to get the specific element, not all.
I have this document:
{
"_id" : ObjectId("53b1b7dcb830980744687bd4"),
"i_nombre" : "Centro Comercial",
"i_direccion" : {
"i_d_pais" : "Panamá",
"i_d_ciudad" : "Panamá",
"i_d_provincia" : "Panamá",
"i_d_distrito" : "Chilibre",
"i_d_corregimiento" : "Alcalde Diaz",
"i_d_calle" : "Primera"
},
"i_correo_e" : "imqv#imqv.com.pa",
"i_telefono" : {
"i_t_iglesia" : "268-5000",
"i_t_colegio" : "268-5001",
"i_t_radio" : "268-5002"
},
"i_estado" : 1,
"i_sector" : [
{
"_id" : ObjectId("53b6d903b8309826e891eefe"),
"i_s_color" : "Amarillo",
"i_s_localizacion" : {
"i_s_l_provincia" : "Panamá",
"i_s_l_distrito" : "Chilibre",
"i_s_l_corregimiento" : "San Miguelito"
},
"i_s_supervisor" : []
},
{
"_id" : ObjectId("53b6d903b8309826e89100f0"),
"i_s_color" : "Rojo",
"i_s_localizacion" : {
"i_s_l_provincia" : "Panamá",
"i_s_l_distrito" : "Arraijan",
"i_s_l_corregimiento" : "Burunga"
},
"i_s_supervisor" : []
},
{
"_id" : ObjectId("53b6d903b8309826e89220f0"),
"i_s_color" : "Azul",
"i_s_localizacion" : {
"i_s_l_provincia" : "Panamá",
"i_s_l_distrito" : "Colon",
"i_s_l_corregimiento" : "Chilibre"
},
"i_s_supervisor" : []
}
]
};
When i execute this query on mongodb
db.iglesia.find
(
{ "_id" : ObjectId("53b1b7dcb830980744687bd4") }
, {
i_sector: {
$elemMatch: { "_id" : ObjectId("53b6d903b8309826e891eefe") }
}
}
);
i get:
{
"_id" : ObjectId("53b1b7dcb830980744687bd4"),
"i_sector" : [
{
"_id" : ObjectId("53b6d903b8309826e891eefe"),
"i_s_color" : "Amarillo",
"i_s_localizacion" : {
"i_s_l_provincia" : "Panamá",
"i_s_l_distrito" : "Chilibre",
"i_s_l_corregimiento" : "San Miguelito"
},
"i_s_supervisor" : []
}
]
}
Question: How i can get the same result with C#? Just with the $elemMatch that i set on Query.
The reason is that your Mongo shell query is not a find with 2 filters, by church id and sector, it is actually a find by church id and a projection by sector id. You have arranged the braces funny, that's all.
This has 2 filters and no projection:
db.iglesia.find ({"_id": "53b1b7dcb830980744687bd4", i_sector: { $elemMatch: {"_id" : "53b6d903b8309826e891eefe"}}}).pretty()
This has a filter and projection:
db.iglesia.find ({"_id": "53b1b7dcb830980744687bd4"}, {i_sector: { $elemMatch: { "_id": "53b6d903b8309826e891eefe"}}}).pretty()
A complete C# example, for these 2 cases using a newer driver, version 2.3, here on rextester.

Categories

Resources