C# Conditionally looping through JSON values - c#

I am new to this and apologize if it is a duplicate question. I have tried so many different things at this point I'm not sure the right way to do this.
I am trying to write a function to loop through a JSON and get the value of model for certain conditions (ie: qty != null, and sector = 1, position = 1.
I also need to count the number of occurrences for each unique model.
Any help would be greatly appreciated.
Here is what the JSON looks like.
[ { "sector": "1", "position": "1", "qty": "1", "model": "SBNHH-1D65C" },
{ "sector": "2", "position": "1", "qty": "1", "model": "" },
{ "sector": "3", "position": "1", "qty": "1", "model": "DC6-48-60-18-8F" },
{ "sector": "1", "position": "2", "qty": "1", "model": "SBNHH-1D65C" },
{ "sector": "2", "position": "2", "qty": "1", "model": "DC6-48-60-18-8F" } ]
public class AntennaItems
{
public AntennaItems[] root { get; set; }
public int sector { get; set; }
public int position { get; set; }
public string qty { get; set; }
public string model { get; set; }
}
string requestBodyString = await new StreamReader(req.Body).ReadToEndAsync();
var newJsonString = #"{root:" + requestBodyString + #"}";
List<string> modelList = new List<string>();
var jsonObj = JsonConvert.DeserializeObject<AntennaItems>(newJsonString);
foreach (var elem in jsonObj.root)
{
modelList.Add(elem.model);
}
return new OkObjectResult($"modelList = {modelList}");
Currently I'm getting this response:
modelList = System.Collections.Generic.List`1[System.String]

You'd return your modelList in interpolation with string name modelList and interpolation return you the type of your modelList and in your case its a System.Collections.Generic.List'1[System.String].
So this line
return new OkObjectResult($"modelList = {modelList}");
Give you
modelList = System.Collections.Generic.List`1[System.String]
So instead of returning like above try to return your modelList with anonymous type so you will be able to get actual data containing modelList like
return new OkObjectResult(new { modelList = modelList});
Or Simply
return new OkObjectResult(modelList);

I think you don't need root property. I have modified the class little bit and removed the root property from it:
public class AntennaItems
{
public int sector { get; set; }
public int position { get; set; }
public string qty { get; set; }
public string model { get; set; }
}
public HttpResponse ParseJson()
{
string requestBodyString = await new StreamReader(req.Body).ReadToEndAsync();
var newJsonString = #"{root:" + requestBodyString + #"}";
List<string> modelList = new List<string>();
var jsonObj = JsonConvert.DeserializeObject<List<AntennaItems>>(newJsonString);
foreach (var elem in jsonObj)
{
modelList.Add(elem.model);
}
return new OkObjectResult($"modelList = {modelList}");
}
You need to deserialize it in List. Let me know if it helps.

public class AntennaItems
{
public int sector { get; set; }
public int position { get; set; }
public string qty { get; set; }
public string model { get; set; }
[FunctionName("AntennaSort")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
List<string> modelList = new List<string>();
var jsonObj = JsonConvert.DeserializeObject<List<AntennaItems>>(requestBody);
foreach (var elem in jsonObj)
{
modelList.Add(elem.model);
}
return new OkObjectResult($"modelList = {modelList}");
}
The result is
modelList = System.Collections.Generic.List`1[System.String]

Related

JSON convert array type to list in C#

I have some array data coming from an API in JSON format, and I want to convert an array type to a list. There is an ASP.NET MVC project and I used the list in Index page. How can I deserialize the array format into a list?
Controller
public async Task<IActionResult> ListCountries()
{
List<Country> countries = new List<Country>();
HttpClient _client = new HttpClient();
HttpResponseMessage _response = new HttpResponseMessage();
_client = _apiHelper.Initial();
_response = await _client.GetAsync("api/Countries/getall");
if (_response.IsSuccessStatusCode)
{
var results = _response.Content.ReadAsStringAsync().Result;
countries = JsonConvert.DeserializeObject<List<Country>>(results);
}
return View(countries);
}
Data
"data": [
{
"id": 1,
"countryName": "Afghanistan"
},
{
"id": 2,
"countryName": "Albania"
},
{
"id": 3,
"countryName": "Algeria"
},
Entity
public class Country
{
[Key]
public int Id { get; set; }
public string CountryName { get; set; }
}
Your json data is invalid format. Json maybe have to be like this:
{
"data": [
{
"id": 1,
"countryName": "Afghanistan"
},
{
"id": 2,
"countryName": "Albania"
},
{
"id": 3,
"countryName": "Algeria"
}
]
}
After that you should create 2 c# class like this:
public class JsonData
{
public List<Country> data { get; set; }
}
public class Country
{
public int id { get; set; }
public string countryName { get; set; }
}
Then you can deserialize it without any error.
public async Task<IActionResult> ListCountries()
{
List<Country> countries = new List<Country>();
HttpClient _client = new HttpClient();
HttpResponseMessage _response = new HttpResponseMessage();
_client = _apiHelper.Initial();
_response = await _client.GetAsync("api/Countries/getall");
if (_response.IsSuccessStatusCode)
{
var results = _response.Content.ReadAsStringAsync().Result;
countries = JsonConvert.DeserializeObject<JsonData>(results);
}
return View(countries);
}
The object has a variable data that contains the countries whereas the class you're trying to serialize to does not.
Having a class such as:
public class Country{
[JsonProperty('data')]
public List<data> Details {get;set;}
public Country(){
Details = new List<data>();
}
public class data{
[Key]
[JsonProperty('id')]
public int Id { get; set; }
[JsonProperty('countryName')]
public string CountryName { get; set; }
}
and then to deserialize it you would need:
countries = JsonConvert.DeserializeObject<Country>(results);
When it deserializes the object it will map data to the Details variable in the class Country and map each value in the response array to the data class
The structure shown is not a list/array of Countries but an object which has a property data which is a list/array of Contries:
public class Result
{
public List<Country> Data {get; set;}
}
...
var r = JsonConvert.DeserializeObject<Result>(results);
var countries = r.Data;
Minor note. Since you're using Json.NET it's OK that your properties don't match the case in json, but if you switch to System.Text.Json this would become an issue.
you have to parse and use JArray inside of your result
var countries = JObject.Parse(results)["data"].ToObject<List<Country>>();
// data for test
var results = #"{""data"": [
{
""id"": 1,
""countryName"": ""Afghanistan""
},
{
""id"": 2,
""countryName"": ""Albania""
},
{
""id"": 3,
""countryName"": ""Algeria""
}]}";

Mongodb C# Update element in an multiple array with multiple values

I want to update the single document in collection with the guid as filter and update value is cityType. Every guid has different citytype here i have used 3 types it may be more.
So please give a right implementation using c# code.
Models:
public class Country
{
[BsonId]
public ObjectId Id { get; set; }
public int CountryId {get; set; }
public IEnumerable<States> States { get; set; }
}
public class States
{
public Guid Guid { get; set; }
public CityType CityType { get; set; }
}
Enum CityType
{
Unknown = 0,
Rural = 1,
Urban = 2
}
Existing Collection:
{
"_id": ObjectId("6903ea4d2df0c5659334e763"),
"CountryId": 200,
"States": [
{
"Guid": "AFCC4BE7-7585-5E46-A639-52F0537895D8",
"CityType": 0,
},
{
"Guid": "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
"CityType": 0,
}
}
Input:
List<States>()
{
new States()
{
Guid = "AFCC4BE7-7585-5E46-A639-52F0537895D8",
CityType = CityType.Rural
},
new States()
{
Guid = "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
CityType = CityType.Urban
}
}
Expected:
{
"_id": ObjectId("6903ea4d2df0c5659334e763"),
"CountryId": 200,
"States": [
{
"Guid": "AFCC4BE7-7585-5E46-A639-52F0537895D8",
"CityType": 1,
},
{
"Guid": "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
"CityType": 2,
}
}
This is the method I have tried:
public async Task<bool> UpdateType(int countryId, IEnumerable<States> states)
{
var collection = connectionFactory.GetCollection<Country>(collectionName);
var cityTypes = states.Select(x => x.CityType);
var filter = Builders<Country>.Filter.Empty;
var update = Builders<Country>.Update.Set("States.$[edit].CityType", cityTypes);
var arrayFilters = new List<ArrayFilterDefinition>();
foreach (var state in states)
{
ArrayFilterDefinition<Country> optionsFilter = new BsonDocument("state.Guid", new BsonDocument("$eq", state.Guid));
arrayFilters.Add(optionsFilter);
}
var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
var result = await collection.UpdateOneAsync(filter, update, updateOptions);
return result;
}
hope all details I have added here. Thanks in advance.
You don't have to loop through it:
Let's say you have a Class1 like this:
class Question : AuditableEntity {
public string Text { get; set; }
public List<string> Tags { get; set; } = new List<string>();
so you just say:
await collection.UpdateOneAsync(
someFilter,
Builders<Class1>.Update
.Set(f => f.Text, request.Question.Text)
.Set(f => f.Tags, request.Question.Tags));

Parsing JSON with JObject

I need to parse a JSON, I am already parsing the first part of the record but I am having a problem with a sub record. This is my code:
List<JToken> results = new List<JToken>();
List<JToken> results2 = new List<JToken>();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
results = JObject.Parse(result).SelectToken("record").ToList();
}
List<Record> users = new List<Record>();
foreach (JObject token in results)
{
Record user = new Record();
user.id = Int32.Parse(token["id"].ToString());
user.full_name = token["full_name"].ToString();
user.email = token["email"].ToString();
//role.RoleName = token.SelectToken("name").ToString();
}
That's working perfectly but I have issues parsin a string that's a bit deeper. This is the JSON:
{
"record": [
{
"id": 2,
"institution_id": 1,
"full_name": "",
"email": "",
"role_id": 2,
"created": "2015-01-13 01:18:52.370379",
"updated": "2015-01-22 23:58:44.103636",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "Test Branch"
}
}
]
}
I want to get the "branch_name" inside Branch_by_branch_id. How can I access it with Jobject?
If your JSON is this
{
"record": [
{
"id": 26,
"full_name": "",
"email": "",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "NAME"
}
}
]
}
Have classes like this:
public class BranchByBranchId
{
public int id { get; set; }
public int institution_id { get; set; }
public string branch_name { get; set; }
}
public class Record
{
public int id { get; set; }
public string full_name { get; set; }
public string email { get; set; }
public int branch_id { get; set; }
public BranchByBranchId Branch_by_branch_id { get; set; }
}
public class RootObject
{
public List<Record> record { get; set; }
}
Then parse it and retrieve the value like this.
var root = JsonConvert.DeserializeObject<RootObject>(json);
var branchName = root[0].Branch_by_branch_id.branch_name;
I always prefer to access my JSON objects like this, because I like having my objects as native C# classes. The classes were generated by json2csharp.

How to Get Values from a json response string in C#

I want to get "id" "gender", "name", "picture" from a this json response string
{
"data": [{
"name": "XXX",
"gender": "male",
"id": "528814",
"picture": {
"data": {
"is_silhouette": false,
"url": "https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-frc3\/v\/t1.0-1\/p50x50\/551182_10152227358459008__n.jpg?oh=983b70686285c2f60f71e665ace8ed5f&oe=54C1220C&__gda__=1422017140_998fbe013c4fe191ccadfdbc77693a76"
}
}
}
string[] data = friendsData.Split(new string[] { "}," }, StringSplitOptions.RemoveEmptyEntries).ToArray();
foreach (string d in data)
{
try
{
FacebookFriend f = new FacebookFriend
{
id = d.Substring("\"id\":\"", "\""),
gender = d.Substring("gender\":\"", "\""),
name = d.Substring("name\":\"", "\""),
picture = d.Substring("\"picture\":{\"data\":{\"url\":\"", "\"").Replace(#"\", string.Empty)
};
FacebookFriendList.Add(f);
}
catch
{
continue;
}
}
This code looks bad if the json data changes then you need to modify your logic accordingly. I would suggest you to serialize and deserialize the model data using Json serialization.
Model:
public class SerializationModel
{
public Data Data { get; set; }
}
public class Data
{
public string Name { get; set; }
public string Gender { get; set; }
public string Id { get; set; }
public Picture Picture { get; set; }
}
public class Picture
{
public PictureData Data { get; set; }
}
public class PictureData
{
public bool is_silhouette { get; set; }
public string url { get; set; }
}
Serialize your data to get the json output is like,
SerializationModel serializationModel = new SerializationModel
{
Data = new Data
{
Gender = "mALE",
Id = "88",
Name = "User",
Picture = new Picture
{
Data = new PictureData
{
is_silhouette = true,
url = "www.google.com"
}
}
}
};
string serializedString = Newtonsoft.Json.JsonConvert.SerializeObject(serializationModel);
which would yield the below result,
{"Data":{"Name":"User","Gender":"mALE","Id":"88","Picture":{"Data":{"is_silhouette":true,"url":"www.google.com"}}}}
To deserialize the json data back to the model,
SerializationModel sm = Newtonsoft.Json.JsonConvert.DeserializeObject<SerializationModel>(serializedString);
Then you can get the required values from the model itself.

Read JSON string as key value

I have following json:
{
"serverTime": "2013-08-12 02:45:55,558",
"data": [
{
"key1": 1,
"key2": {},
"key3": {
"key4": [
""
],
"key5": "test2"
},
"key7": 0
},
{
"key8": 1,
"key9": {},
"key10": {
"key4": [
""
],
"key9": "test2"
},
"key11": 0
}
]
}
I want to get values as key value pair. Something like:
jsonObject[data][0]
should give first item of the data array.
I am using JSONFx.net. But it gives strongly typed objects. I do not want that.
Is there any way to parse JSON as key value as I mentioned earlier?
Thanks
Try this:
using System;
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("input.txt");
var a = new { serverTime = "", data = new object[] { } };
var c = new JsonSerializer();
dynamic jsonObject = c.Deserialize(new StringReader(json), a.GetType());
Console.WriteLine(jsonObject.data[0]);
}
}
If you're not averse to using Json.NET, you can do this:
var jsonString = #"
{
""serverTime"": ""2013-08-12 02:45:55,558"",
""data"": [
{
""key1"": 1,
""key2"": {},
""key3"": {
""key4"": [
""""
],
""key5"": ""test2""
},
""key7"": 0
},
{
""key8"": 1,
""key9"": {},
""key10"": {
""key4"": [
""""
],
""key9"": ""test2""
},
""key11"": 0
}
]
}";
var jsonResult = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
var firstItem = jsonResult["data"][0];
firstItem would be an array of the first item in the data array:
Hope this helps.
First create classes to parse string
public class Key2
{
}
public class Key3
{
public List<string> key4 { get; set; }
public string key5 { get; set; }
}
public class Key9
{
}
public class Key10
{
public List<string> key4 { get; set; }
public string key9 { get; set; }
}
public class Datum
{
public int key1 { get; set; }
public Key2 key2 { get; set; }
public Key3 key3 { get; set; }
public int key7 { get; set; }
public int? key8 { get; set; }
public Key9 key9 { get; set; }
public Key10 key10 { get; set; }
public int? key11 { get; set; }
}
public class RootObject
{
public string serverTime { get; set; }
public List<Datum> data { get; set; }
}
add reference of Newtonsoft.Json.dll
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonData);
then you can access values .
If you want to do this without third party libraries then do:
I would use the following code:
var deserializer = new JavaScriptSerializer();
var someObject = deserializer.DeserializeObject(json);
string serverTime = someObject["serverTime"].ToString();
Dictionary<string, int> data = someObject["data"] as Dictionary<string, int>;
Give it a go.
Edit: You may need to change the last line to:
Dictionary<string, int?> data = someObject["data"] as Dictionary<string, int?>;

Categories

Resources