Parsing string into key value pairs C# [duplicate] - c#

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 2 years ago.
I have method where I call another API. From
var activeCustomers = await response.Content.ReadAsStringAsync();
I get string which contains [timestamp, value] objects:
{"values":[[1298937600000,1],[1459468800000,16],[1462060800000,527],[1464739200000,173],[1467331200000,132],[1470009600000,166],[1472688000000,151],[1475280000000,172],[1477958400000,139],[1480550400000,129],[1483228800000,116],[1485907200000,133],[1488326400000,180],[1491004800000,227],[1493596800000,281],[1496275200000,263],[1498867200000,230],[1501545600000,326],[1504224000000,403],[1506816000000,442],[1509494400000,1019],[1512086400000,650],[1514764800000,708],[1564617600000,2614],[1567296000000,2527],[1569888000000,3144],[1572566400000,3075],[1575158400000,2541],[1577836800000,2246],[1580515200000,2456],[1583020800000,885]]}
I want to parse these values into key value pairs, but I am not sure what's the most optimal way for that.
I tried removing beginning and ending of string and cast it as object but it stays as one big string inside the ienumerable:
int index = activeCustomers.IndexOf(":");
if (index > 0)
activeCustomers = activeCustomers.Substring(index + 1);
activeCustomers = activeCustomers.Remove(activeCustomers.Length - 1);
var results = ((IEnumerable) activeCustomers).Cast<object>();
I also tried making regex for that but I am not very comfortable with that.

This just a JSON with array of arrays, which can be easily deserialized using Json.NET
var result = JsonConvert.DeserializeObject<Root>(activeCustomers);
or System.Text.Json
var result = JsonSerializer.Deserialize<Root>(activeCustomers);
Where Root is
public class Root
{
public long[][] values { get; set; }
}
Then you can map the values property to any desired structure using Select method
var pairs = result.values.Select(v => new { timestamp = v[0], value = v[1] }).ToList();

Related

C# - dictionary - How to get max of specific class value in dictionary? [duplicate]

This question already has answers here:
How to get MAX value from Dictionary?
(8 answers)
Closed 2 years ago.
I have a dictionary where I'm trying to find the max of a specific class value, similar to getting max of a list. I've been searching for a couple of hours but all I'm finding is how to grab a value from a dictionary that has a key and a single value. I've also come across Linq but I'm not finding anything on how to search a dictionary's class values for the Max value. I'm pretty sure there is a way and I'm just missing something?
In my case, I'm trying to find the Max lineDistance of my class LineInfo
Links that I have found are close
this one but it only deals with a single key and a single value, not a class
this one seems like it might be on the right track but the checked answer suggests to run a nested foreach. I would imagine there's an easier / more sosphisticated way?
Any and all help is appreciated.
here is my code, it's fairly simple:
class LineInfo
{
public double lineDistance { get; set; }
public LineSegment2d lineSegment2D1 { get; set; }
public LineSegment2d lineSegment2D2 { get; set; }
}
var lines = new Dictionary<int, LineInfo>();
double pointDistance0 = lineSegment2DList[i].StartPoint.GetDistanceTo(lineSegment2DList[j].StartPoint);
lines.Add(0, new LineInfo {lineDistance = pointDistance0, lineSegment2D1 = lineSegment2DList[i], lineSegment2D2 = lineSegment2DList[j] });
double pointDistance1 = lineSegment2DList[i].StartPoint.GetDistanceTo(lineSegment2DList[j].EndPoint);
lines.Add(1, new LineInfo { lineDistance = pointDistance1, lineSegment2D1 = lineSegment2DList[i], lineSegment2D2 = lineSegment2DList[j] });
double pointDistance2 = lineSegment2DList[i].EndPoint.GetDistanceTo(lineSegment2DList[j].StartPoint);
lines.Add(2, new LineInfo { lineDistance = pointDistance2, lineSegment2D1 = lineSegment2DList[i], lineSegment2D2 = lineSegment2DList[j] });
double pointDistance3 = lineSegment2DList[i].EndPoint.GetDistanceTo(lineSegment2DList[j].EndPoint);
lines.Add(3, new LineInfo { lineDistance = pointDistance3, lineSegment2D1 = lineSegment2DList[i], lineSegment2D2 = lineSegment2DList[j] });
To get LineInfo with maximum lineDistance you can use Values collection. Since there is no MaxBy in standard LINQ you can achieve similar effect with Aggregate:
var max = lines.Values
.Aggregate((acc, curr) => acc.lineDistance > curr.lineDistance ? acc: curr);
If I'm understanding the question correctly, there's an overload for Max in Linq which allows you to specify a property, i.e:
double max = lines.Max(x => x.Value.lineDistance);
Edit
If you're wanting the object, than #itsme86 solution works the best:
LineInfo maxLineInfo = lines.Values.OrderByDescending(line => line.lineDistance).First();

Convert JSON Key into Object [duplicate]

This question already has answers here:
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
(22 answers)
Closed 2 years ago.
I have a scnerio where i donot know the names of the keys so properties can;t be created beforehand.
The JSON needs to be parsed and loaded into Dictionary that is present in a class.
The format of JSON is like
"SearchCriteria":{
"firstname":"user1",
"surname":"User2"
},
"RequiredGroups":{
"UserGroup":"g1",
"TeacherGroup":"g2"
}
The problem is that the Parameters count and name are not known and can be anything.
The JSON also contains other sections as well such as RequiredGroups which have known key names and are mapped with Objects.
Need to convert into Dictionary. Any leads....
Example using Newtonsoft.Json.Linq:
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"{'SearchCriteria':{'firstname':'user1','surname':'User2'},'RequiredGroups':{'UserGroup':'g1','TeacherGroup':'g2'}}";
JObject o = JObject.Parse(json);
var dict = o.ToObject<Dictionary<string, object>>();
}
}
string str1 = "{\"SearchCriteria\":{ \"firstname\":\"user1\", \"surname\":\"User2\" }, \"RequiredGroups\":{ \"UserGroup\":\"g1\",\"TeacherGroup\":\"g2\" }}";
var jObject1 = JObject.Parse(str1);
Dictionary<string, string> dictObj = new Dictionary<string, string>();
IList<string> keys = jObject1.Properties().Select(p => p.Name).ToList();
foreach(var k in keys)
{
var s = jObject1[k].ToString();
dictObj.Add(k, s);
}

Retrieve a value among several json fields if this one is equal to another value of this json [duplicate]

This question already has answers here:
Get values from dynamic JSON properties C#
(2 answers)
Closed 2 years ago.
I'm sorry if I'm asking a trivial question but I'm stuck so I'm asking for your help.
I currently have a dynamic json that I receive, and I would like that according to the value of the phone the corresponding field is retrieved.
For exemple in my foreach(var item in jsonResult),
if item["Phone"].Value = "PSTN"( or "UIFN", "TS", "RS", "TF" ) then I would like to retrieve the json field which corresponds with its value, in this case it would be "PSTN".
If anyone has an idea how I can make this happen.
Thank you in advance for your answers and your help.
I believe this post can help you.
Try this code:
JObject jObject = JObject.Parse(jsonResult);
var result = (JObject)jObject["put here your top node level"];
foreach(JProperty prop in result.Properties())
{
if (prop.Name == item["Phone"].Value)
{
var values = jObject["put here your top node level"][prop.Name].Values<string>(item["Phone"].Value);
// do something
}
}
You could do it like this. thang.json is a file with json you provided.
var json = File.ReadAllText("thang.json");
var deserialized = JsonConvert.DeserializeObject<dynamic>(json);
if (new[] {"PSTN", "UIFN", "TS", "RS", "TF"}.Contains((string) deserialized.Phone))
{
Console.WriteLine(deserialized[(string)deserialized.Phone]);
}

C# Select From Json List Using Where Clause [duplicate]

This question already has answers here:
Find an item in a list by LINQ
(14 answers)
Closed 4 years ago.
I have a json list and I have a type named post. I want to use it for search.
I want to get a list or one object with a query. Is that possible ?
Example part of json
{
"Post": [
{
"id":"22",
"text":"Dream Big",
"img":"a2ca3cf9-664e-4d92-80f1-df20e971b7c0.jpg",
"catid":"12",
"meta_title":"Dream Big Design",
"content":"some text",
"user_id":"5556",
}
{
"id":"24",
"text":"Handmade Resin",
"img":"423233-971b7c0.jpg",
"catid":"7",
"meta_title":"Handmade Resin",
"content":"some text",
"user_id":"1256",
}
]
}
I want to select id = 23 or name like 'handmade'.
I tried with this code but it did not work
string json = System.IO.File.ReadAllText(path + "output.json");
var serializer = new JavaScriptSerializer();
Post post = JsonConvert.DeserializeObject<Post>(json);
you can use JObject in the C# that can parse the Json object and then you can fire your Select query.
JObject jObject = JObject.Parse(your Json object in string);

convert jsonstring to objects c# [duplicate]

This question already has answers here:
How to Convert JSON object to Custom C# object?
(13 answers)
Closed 5 years ago.
i want to get the data from my returning api jsonstring.
my result string looks like this
[
{"Id":12,"name":"testname","type":"testtype"}
{"Id":12,"name":"testname","type":"testtype"}
{"Id":12,"name":"testname","type":"testtype"}
]
how can i extract this data to c# objects
i can only do it ones
var obj = JObject.Parse(result);
var ID = (int)obj["Id"];
var Name = (String)obj["name"];
var type = (String)obj["type"];
User u = new User(ID,Name,Type);
Your string is not valid JSON, so making it valid JSON is the first step to process it quickly. The easiest thing to do is to make it a JSON array:
string jsonArray = "["
+ string.Join(", ", json.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
+ "]";
From then on it is straightforward (see my related answer: Easiest way to parse JSON response):
var result = JsonConvert.DeserializeObject<User[]>(jsonArray);
Another option is to split the lines yourself, and parse and add the items to a list manually.
Result is an array of JSON.. so loop and parse
list<User> userList = new list<User>();
for(int i=0 ; i <result.length; i++)
{
var obj = JObject.Parse(result[i]);
var ID = (int)obj["Id"];
var Name = (String)obj["name"];
var type = (String)obj["type"];
User u = new User(ID,Name,Type); //create User
userList.add(u); //Add to list
}

Categories