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
Related
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
}
]
}
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
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);
}
}
I am trying to consume an API which return a JSON built as :
Team.player1 / player2 / player3... (the players are built as properties and not as an array)
I was thinking to use reflection to do it, but having hard time to get a player.
type Simple = JsonProvider<"sample.json">
let wbReq = "API-FOR-TEAM"
let docAsync = Simple.Load(wbReq)
let allValues = FSharpType.GetRecordFields (docAsync.Team.Players.GetType())
let test = allValues
|> Seq.map (fun p -> (p.GetValue(docAsync.Team.Players) as ?).Name) // HOW TO GET THE TYPED PLAYER HERE ?
|> fun p -> printfn p
EDIT : I tried to use GetType and System.Convert.ChangeType
EDIT2 : Here is a simplified version of the JSON :
{
"Team": {
"id": "8",
"players": {
"17878": {
"info": {
"idteam": 8,
"idplayer": 17878,
"note": 6
}
},
"18507": {
"info": {
"idteam": 8,
"idplayer": 18507,
"note": 5
}
}
}
}
}
Edit 3 :
I found an easy solution in C# (thanks to JSON.net and dynamic) but for learning purpose I would like to do the same in F# if someone wanna help :
private static List<Player> Parse(string jsonString)
{
dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
var players = ParseItems(jsonObject.Home.players);
return players;
}
private static List<Player> ParseItems(dynamic items)
{
List<Player> itemList = new List<Player>();
foreach (var item in items)
{
itemList.Add(new Player()
{
idplayer = item.Value.info.idplayer,
lastName = item.Value.info.lastname,
note = item.Value.info.note
});
}
return itemList;
}
You can mix JsonTypeProvider and parsing Json. For example:
[<Literal>]
let sample = """{
"Team": {
"id": "8",
"players": {
"17878": {
"info": {
"idteam": 8,
"idplayer": 17878,
"note": 6
}
},
"18507": {
"info": {
"idteam": 8,
"idplayer": 18507,
"note": 5
}
}
}
}
}"""
type Player = {IdTeam:int; IdPlayer:int; Note:int}
type Simple = JsonProvider<sample>
let docAsync = Simple.GetSample()
let json = docAsync.Team.Players.JsonValue
let parseInfo (json:JsonValue) =
let id_team = (json.GetProperty "idteam").AsInteger()
let id_player = (json.GetProperty "idplayer").AsInteger()
let note = (json.GetProperty "note").AsInteger()
{IdTeam = id_team; IdPlayer = id_player; Note = note}
let players =
json.Properties()
|> Array.map(fun (_,x) -> x.GetProperty "info")
|> Array.map (parseInfo)
players
|> Array.iter (printfn "%A")
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