How to convert entire DataRow to Key Value pair one by one - c#

I am looking for a solution in c# where I need to convert all DataRow to Key value pair.
Here is what my data is coming as of now,
{
"DynamicColumnsList":
[
{
"myRow":"Title|KeyQuestion|OfferingBanner|OfferingOverview|Image_x0020_Icon|KeyContacts|KeyContacts_x003a_ID|KeyInvestmentAreas|KeyIssuesMarketDrivers|KeyServices|TypicalBuyers|AdditionalColumn1|Base64Image|Base64Banner|FSOCrossSector|ID"
},
{
"myRow":"BigBetsTestTier1|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|SomeData|14"
}
{
"myRow": "....."
}
{
"myRow": "....."
}
{
"myRow": "....." and so on...
}
]
}
The First myRow has column names and below that Second myRow has the respective values of it and so on till 10 rows.
So is there any possible way to have data like below format,
{
"DynamicColumnsList":
[
{
"Title": "BigBetsTestTier1",
"KeyQuestion": "SomeData",
"OfferingBanner": "SomeData",
"OfferingOverview": "SomeData",
"Image_x0020_Icon": "SomeData",
"KeyContacts": "SomeData",
"KeyContacts_x003a_ID":"SomeData",
"KeyInvestmentAreas":"SomeData",
"KeyIssuesMarketDrivers":"SomeData",
"KeyServices":"SomeData",
"TypicalBuyers":"SomeData",
"AdditionalColumn1":"SomeData",
"Base64Image":"SomeData",
"Base64Banner":"SomeData",
"FSOCrossSector":"SomeData",
"ID":"14"
},
{
...
},
{
... and so on
}
]
}

Related

Error when trying to pass a string into a json object c# - Current JsonReader item is not an object

I am trying to pass my variable query as a Json object. So I saw online that one way to do so is by doing JObject.Parse(). I attempted to do so, but when debugging I noticed that .Parse() would create a "{" at the beginning and a "}" at the end of the contents of the variable query. So I then attempted to remove the first "{" and last "}" inside of query but whenever I would hit the JObject.Parse() line, it would throw an exception saying:
Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 6.
So I then attempted to use the code after query, but this would still give me the same error when I hit the next line that consisted of JObject.Parse():
if (query.Length > 2){
query = query.Substring(1, s.Length-2)
}
So then I saw online that another way to get around this error is to use the following, but it would not remove the first "{" and last "}".
query = query.TrimStart(new char[] { '{' }).TrimEnd(new char[] { '}' });
This is what my query consists of and what I tried to do to pass query as a json object:
var query = "{\"size\": 1000,\"query\": {\"bool\": {\"should\":[ {\"match\": { \"level\": \"Information\" } }, {\"match\": { \"level\": \"Error\" } } ], " +
"\"filter\": [ { \"range\": { \"#timestamp\": { \"gte\": \"2021-07-26T07:58:45.304-05:00\", \"lt\": \"2021-07-26T08:58:45.305-05:00\" } } } ]," +
"\"minimum_should_match\": 1 } } }";
query = query.TrimStart(new char[] { '{' }).TrimEnd(new char[] { '}' });
/* if (query.Length > 2){
query = query.Substring(1, s.Length-2)
} */
var jsonQuery = JObject.Parse(query);
How would I go about resolving the issue I am having that .Parse() is adding an extra { at the beginning and } and at the end.
Variable Query holds:
{"size": 1000,"query": {"bool": {"should":[ {"match": { "level": "Information" } }, {"match": { "level": "Error" } } ], "filter": [ { "range": { "#timestamp": { "gte": "2021-07-26T07:58:45.304-05:00", "lt": "2021-07-26T08:58:45.305-05:00" } } } ],"minimum_should_match": 1 } } }
Then jsonQuery holds:
{{ "size": 1000, "query": { "bool": { "should": [ { "match": { "level": "Information" } }, { "match": { "level": "Error" } } ], "filter": [ { "range": { "#timestamp": { "gte": "2021-07-26T07:58:45.304-05:00", "lt": "2021-07-26T08:58:45.305-05:00" } } } ], "minimum_should_match": 1 } }}}
If you look closely, .Parse() is adding a { at the beginning and adding another } at the end.
That double parentheses "issue" is just debugger display for JObject in Visual Studio. If you actually try to output JObject as a string, you'll get correct output.
static void Main(string[] args)
{
var query = "{\"size\": 1000,\"query\": {\"bool\": {\"should\":[ {\"match\": { \"level\": \"Information\" } }, {\"match\": { \"level\": \"Error\" } } ], " +
"\"filter\": [ { \"range\": { \"#timestamp\": { \"gte\": \"2021-07-26T07:58:45.304-05:00\", \"lt\": \"2021-07-26T08:58:45.305-05:00\" } } } ]," +
"\"minimum_should_match\": 1 } } }";
var jsonQuery = JObject.Parse(query);
Console.WriteLine(jsonQuery); // all good!
Console.ReadLine();
}
On the side note, I think it would be easier for you to test Elasticsearch with NEST and Elasticsearch.NET nuget packages.

generic api consume class in c#

try
{
HttpResponseMessage httpResponseMessage = GlobalVariables.WebAPI.GetAsync("http://dummy.restapiexample.com/api/v1/employees").Result;
if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
var tupleList = new List<Tuple<dynamic, dynamic>>();
var genericList = JsonConvert.DeserializeObject<IEnumerable<object>>(httpResponseMessage.Content.ReadAsStringAsync().Result);
int _totalColumns = 0;
var allowFirst = false;
foreach ( var genericObject in genericList)
{
allowFirst = true;
if (allowFirst)
{
try
{
Type type = genericObject.GetType();
// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
{
}
}
catch (Exception)
{
}
}
else
{
break;
}
}
}
}
catch (Exception)
{
}
l dont know if this is possible but am trying to create a generic class to consume api.
the data will only be in form of array objects without inner objects on another object like sample
sample 1
[
{
"id": "24",
"employee_name": "Doris Wilder",
"employee_salary": "85600",
"employee_age": "23",
"profile_image": "images/default_profile.png"
},
{
"id": "25",
"employee_name": "Angelica Ramos",
"employee_salary": "1200000",
"employee_age": "47",
"profile_image": "images/default_profile.png"
}
]
Sample Two
[
{
"project_Id": "24",
"project_name": "Lorem Ipsum"
},
{
"project_Id": "25",
"project_name": "Lorem Ipsum ipsum"
}
]
Sample 3
[
{
"Employee_Id": "25",
"Employee_name": "Sam Doe"
},
{
"Employee_Id": "2",
"Employee_name": "Jon doe"
}
]
Upto
Sample 20++ ..................:
m stack on now determining the number of object propertise and how to store it ?
like sampe 1 has four properties
sample 2 has two properties how best can l do that
and determining how to save it:
Edit
l have more than 20 urls { and likely to increase }are different array of objects what l wanted was not to create Strongly typed class as the data is only used to be rendered on an html table string but all the api values will have 0-100 array of object , thus all l want to know if its possible or l will stick to what l was already doing which was mentioned by #nkosi

How to remove the attribute container from JSON in C#?

I have an issue with JSON that contains several elements, and I want to convert some JSON array of objects without the id that contain the element itself. Basically what I want is to convert this structure:
{
"SubscriptionStorages": {
"1": {
"Type": "subscriberstorage",
"SubscriberStorage_Id": 1,
"SubscriberStorage_AdminDescription": "JM Basic",
"SubscriberStorage_MaxStorage": 268435456000
},
"2": {
"Type": "subscriberstorage",
"SubscriberStorage_Id": 2,
"SubscriberStorage_AdminDescription": "JM Standard",
"SubscriberStorage_MaxStorage": 536870912000
}
}
}
to this structure:
{
"SubscriptionStorages": [
{
"Type": "subscriberstorage",
"SubscriberStorage_Id": 1,
"SubscriberStorage_AdminDescription": "JM Basic",
"SubscriberStorage_MaxStorage": 268435456000
},
{
"Type": "subscriberstorage",
"SubscriberStorage_Id": 2,
"SubscriberStorage_AdminDescription": "JM Standard",
"SubscriberStorage_MaxStorage": 536870912000
}
]
}
Is there any simple way to do it?
This is what I have so far, but it's not good...
What am I missing here?
List<string> items = new List<string>();
if (itemsList != null)
{
if (itemsList.Count > 0)
{
JToken outer = JToken.Parse(jsonBody);
foreach (JToken t in outer)
{
items.Add(t.ToString());
}
}
}
return items;
You can transform your JSON like this:
var jo = JObject.Parse(originalJson);
jo["SubscriptionStorages"] = new JArray(
jo["SubscriptionStorages"]
.Children<JProperty>()
.Select(jp => jp.Value)
);
var modifiedJson = jo.ToString();
Fiddle: https://dotnetfiddle.net/9sCx2M

How do i check the datatype of my Jarray? (C#)

I got a method that receives JProperty's of arrays.
This can be a simple arrays of strings: ("Img1.png", "Img2.png" ect). or a array with objects:
{[{
"id": "1",
"name": "name",
"image": "img1.png"},{
"id": "2",
"name": "name",
"image": "img2.png"},
{
"id": "3",
"name": "name",
"image": "img3.png"
}]}"
Within the methods receving the JProperty's different actions need to happen, but i can't get the if-statement to filter the objects too an object event.
This is currently my code:
private static void handleArray(JProperty array)
{
foreach (JArray x in array)
{
JTokenType type = x.Type;
if (type == JTokenType.Object)
{
Console.WriteLine("Array with objects!");
}
else {
foreach (string childrensTokens in x)
//Array with normal strings
Console.WriteLine(childrensTokens);
}
}
}
(the else statement crashes atm because it recieves the objects too.)
Does anyone know how to help me? i tried to get to the childrensTokens but failed.
Fixed it with:
private static void handleArray(JProperty array)
{
//voor de gewone array:
foreach (JArray x in array)
{
foreach (var a in x)
if(a.Type == JTokenType.Object)
{
Console.WriteLine("Array with objects!");
}
else
{
Console.WriteLine((string) a);
}
}

How to access to all JProperties sub values in Json.net?

I`m trying to pars a Json in my C# code with Json.NET.
I want to print the child of each token after the parent.
my JSON string is something like this(but very longer):
{
"type": "ExpressionStatement",
"expression": {
"type": "CallExpression",
"callee": {
"type": "FunctionExpression",
"id": null,
"params": [
{
"type": "Identifier",
"name": "E"
},
{
"type": "Identifier",
"name": "B"
}
]
}
}
}
and I`m trying this code for my purpose and in this first I check value of JProperties and if there was something starts with '[' I sub String it and parse it again other otherwise print that :(r is my Json string)
JObject a = JObject.Parse(r);
ArrayList ab= new ArrayList();
String reg=#"{[-a-zA-Z0-9_~,'"":\s]*}\s*,\s*{[-a-zA-Z0-9~,'"":\s]*}";
ab.Add(a);
for (int i = 0; i < ab.Count; i++ )
{
JObject d=ab[i] as JObject;
foreach (JProperty p in (d.Children()))
{
String val = p.Value.ToString();
if( val.StartsWith("[")){
val=val.Substring(2,val.Length-2);
if(Regex.Match(val,reg).Success)
{
String reg2 = #"},\s*{";
int num=Regex.Match(val,reg2).Index;
String val1 = val.Substring(0,num+1);
JObject newob = JObject.Parse(val1);
ab.Add(newob);
val = val.Substring(num+3);
newob = JObject.Parse(val);
ab.Add(newob);
}
if (!val.Equals("")) {
JObject newob=JObject.Parse(val);
ab.Add(newob);}
}
else if (val.StartsWith("{"))
{
if (!val.Equals(""))
{
JObject newob = JObject.Parse(val);
ab.Add(newob);
}
}
else
{
Console.WriteLine("value is: {0}", p.Value);
}
}
}
but there is always error for sub String....they always are incorrect!
could anyone help me? or offer me new way?
note:I don`t know the JSON string and it is every time different

Categories