serializing nested json c# - c#

Big apologies for the long post. I need to create the below json format for a post to rest api in c#. The below call works and I have used successfully in Postman to add it to the target system.
{
"item": {
"attrs": {
"attr": [{
"name": "IP_Category",
"value": "Miscellaneous"
}, {
"name": "Description",
"value": "Picture of Rabbit"
}, {
"name": "Title",
"value": "A Rabbit"
}
]
},
"resrs": {
"res": [{
"filename": "Rabbit.jpg",
"base64": "/9j/4AAQSkZJR"
}
]
},
"acl": {
"name": "Submitter"
},
"entityName": "IP_Document"
}
}
Based on the research I've done I need to copy and "paste special" into a new class file in visual studio so it can create the class objects based on the json format (Pretty cool!). And this is what it creates:
namespace BasicWebApp
{
public class Rootobject
{
public Item item { get; set; }
}
public class Item
{
public Attrs attrs { get; set; }
public Resrs resrs { get; set; }
public Acl acl { get; set; }
public string entityName { get; set; }
}
public class Attrs
{
public Attr[] attr { get; set; }
}
public class Attr
{
public string name { get; set; }
public string value { get; set; }
}
public class Resrs
{
public Re[] res { get; set; }
}
public class Re
{
public string filename { get; set; }
public string base64 { get; set; }
}
public class Acl
{
public string name { get; set; }
}
}
Problem 1: Why is vs renaming the res json object to to class Re? Is it a reserved word in c#?
Problem 2: I know I have to nest things in this fashion but I two levels deep and not sure what to code?
var model = new Rootobject();
model.item = new Item
{
attrs = new Attrs
{
attr = new List<Attr>
{
**now what??**
}
}
}

Don't have answer to your first question yet(but looking for it):
For your second question, at now what part you just do:
new Attr(){ name = "name1", value = "value1" },
new Attr(){ name = "name1", value = "value2" }
But that's not what i advise. I advise you to have your Attr collection ready then assign it. Like:
var model = new Rootobject();
model.item = new Item
{
attrs = yourAttrCollection
}
It also goes for everyting else you do. Have your stuff ready, then assign them. It increases readability in nested objects.

Problem 1: Why is vs renaming the res json object to to class Re? Is it a reserved word in c#?
No Re is not reserved word in class.
As mentioned by TheGeneral
res is plural for re's
You can use JsonProperty attribute to resolve this issue like
public class Resrs
{
[JsonProperty("res")]
public Re[] res { get; set; }
}
Problem 2: I know I have to nest things in this fashion but I two levels deep and not sure what to code?
var model = new Rootobject();
model.item = new Item
{
attrs = new Attrs
{
attr = new List<Attr>
{
new Attr { name = "abc", value = "ABC" },
new Attr { name = "pqr", value = "PQR" }
}
}
}

Thanks to all that responded. It helped. I ended up using the below code to create the json object I needed.
var model = new RootObject();
model.item = new Item
{
attrs = new Attrs
{
attr = new List<Attr>
{
new Attr { name = "IP_Category", value = ddlContent.Text },
new Attr { name = "Description", value = txtDesc.Text },
new Attr { name = "Title", value = txtTitle.Text }
}
},
resrs = new Resrs
{
res = new List<Re>
{
new Re { filename = fName, base64 = base64string},
}
},
acl = new Acl
{
name = "Submitter"
},
entityName = "IP_Document"
};

Related

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));

How to read json string in c#

I am trying to parse manually a string in json. This is how my json look like
{{
"dbViews": [
{
"viewID": 0,
"viewColumns": [
{
"dbTitle": "ColNmid",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
},
{
"dbTitle": "ColNmdelete",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
}
]
}
],
"AddViewName": "test"
}}
This is how i am trying to read it.
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.id = obj.dbViews.viewID;
User.viewName = obj.AddViewName;
foreach (var item in obj.viewColumns)
{
if (obj.dbTitle == "ColNmid")
{
User.ColNmid = obj.viewTitle;
}
}
I can only read addViewName, i can't seem to access viewID or viewColumn.
Update:
after the comments I obviously miss the second array. Here my new code witch work
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.viewName = obj.AddViewName;
foreach (var view in obj.dbViews)
{
User.id = view.viewID;
foreach (var item in view.viewColumns)
{
if (item.dbTitle == "ColNmid")
{
User.ColNmid = item.viewTitle;
}
}
}
Your json in question is invalid (extra { and } at start and end). It seems that you are using Newtonsoft's Json.NET library. Usual approach is to create model corresponding to your json structure and deserialize it:
public class Root
{
[JsonProperty("dbViews")]
public List<DbView> DbViews { get; set; }
[JsonProperty("AddViewName")]
public string AddViewName { get; set; }
}
public class DbView
{
[JsonProperty("viewID")]
public long ViewId { get; set; }
[JsonProperty("viewColumns")]
public List<ViewColumn> ViewColumns { get; set; }
}
public class ViewColumn
{
[JsonProperty("dbTitle")]
public string DbTitle { get; set; }
[JsonProperty("viewTitle")]
public string ViewTitle { get; set; }
[JsonProperty("activated")]
public bool Activated { get; set; }
[JsonProperty("activatedLabel")]
public string ActivatedLabel { get; set; }
}
var result = JsonConvert.DeserializeObject<Root>();
You don't need to include all properties in your class, you can include only needed ones.
If you don't want to create custom models and want to loop through the JObject properties in your case you can do it for example like that:
var jObj = JObject.Parse(json);
foreach(var view in jObj["dbViews"]) // dbViews is an array
{
Console.WriteLine(view["viewID"]);
foreach (var viewColumn in view["viewColumns"]) // viewColumns is an array
{
Console.WriteLine(viewColumn["dbTitle"]);
}
}

Create Serialize JSON List Type object from c# class

Dear All I am using C# Class and make the json object but how it call it.
and show the json object I am show the code please help me.
Here I am create a class
public class Contacts
{
public List<PhoneMobile> phoneMobiles { get; set; }
public List<PhoneLandline> phoneLandlines { get; set; }
public List<Email> emails { get; set; }
}
public class PhoneMobile
{
public string phoneMobile { get; set; }
}
Here i am use the class like this
contacts = new Contacts
{
phoneMobiles = new List<PhoneMobile>
{
},
phoneLandlines = new List<PhoneLandline>(),
emails = new List<Email>(),
}
I want SerializeObject Like This objects give how to put a value and make it.
"contacts": {
"phoneMobiles": [
{
"phoneMobile": "8103267511"
}
],
"phoneLandlines": [
{
"phoneLandLineNumber": "8103267511"
}
],
"emails": [
{
"email": "testing#gmail.com"
}
]
},
"contactPerson": [
{
"personName": "TEST KARKHANA",
"owner": "null",
"email": "sanjeet.kumar#mponline.gov.in",
"phone": "8602865989"
}
],
How To Make It Please Help
Use Json.Net library, you can download it from Nuget.
Try this
var contactCollection = new Contacts
{
phoneMobiles = new List<PhoneMobile>
{
new PhoneMobile { phoneMobile = "8103267511" }
},
phoneLandlines = new List<PhoneLandline>()
{
new PhoneLandline { phoneLandLineNumber = "8103267511" }
},
emails = new List<Email>()
{
new Email { email = "testing#gmail.com" }
}
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(contacts);
It will serialize object to json except contactPerson section
If you need serialize object with root name contacts then try
var collectionWrapper = new {
contacts = contactCollection
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(collectionWrapper);
then the result will be like:
{"contacts":{"phoneMobiles":[{"phoneMobile":"8103267511"}], "phoneLandlines":[{"phoneLandLineNumber":"8103267511"}], "emails":[{"email":"testing#gmail.com"}]}}

Get value from IEnumerable foreach loop

I need to create a c# object from a JSON file, and have to following working solution:
JSON:
{
"AK": {
"Anchorage": [{
"Name": "John Doe",
"Address": "123 Main St.",
"City": "Anchorage",
"State": "AK",
"Zip": "12345"
}],
"Fairbanks": [{
"Name": "Sally Smith",
"Address": "987 Main St.",
"City": "Fairbanks",
"State": "AK",
"Zip": "98765"
}]
}
}
Code:
public class Location
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
// ------------------------------------------------------------------
string json = File.ReadAllText(#"C:json.txt");
dynamic deserialisedJson = JsonConvert.DeserializeObject(json);
var locations = new List<Location>();
foreach (var root in deserialisedJson)
{
foreach (var state in root)
{
foreach (var city in state)
{
foreach (var location in city)
{
Location loc = new Location();
loc.Name = location.First["Name"];
loc.Address = location.First["Address"];
loc.City = location.First["City"];
loc.State = location.First["State"];
loc.Zip = location.First["Zip"];
locations.Add(loc);
}
}
}
}
But I need to incorporate the above into an SSIS package, which only allows .NET 3.5 and below. The line of code below requires .NET 4.0 and above:
dynamic deserialisedJson = JsonConvert.DeserializeObject(json);
I'm trying to workaround this limitation by using IEnumerable, but I'm not sure of the syntax of how to grab the values I need?
string json = File.ReadAllText(#"C:json.txt");
var deserialisedJson = (IEnumerable)JsonConvert.DeserializeObject(json);
var locations = new List<Location>();
foreach (var root in deserialisedJson)
{
foreach (var state in (IEnumerable)root)
{
foreach (var city in (IEnumerable)state)
{
foreach (var location in (IEnumerable)city)
{
Location loc = new Location();
loc.Name = //What goes here???
loc.Address = //What goes here???
loc.City = //What goes here???
loc.State = //What goes here???
loc.Zip = //What goes here???
locations.Add(loc);
}
}
}
}
This uses Linq to JSON to select all the Location objects you want:
var deserialisedJson = (IEnumerable)JsonConvert.DeserializeObject(json);
JObject jObj = JObject.Parse(json);
//Get all tokens that are under AK/(some descendant)/all items from collection
var result = jObj.SelectTokens("AK.*.[*]")
.Select(x => new Location
{
Name = x["Name"].Value<string>(),
Address = x["Address"].Value<string>(),
City = x["City"].Value<string>(),
State = x["State"].Value<string>(),
Zip = x["Zip"].Value<string>(),
}).ToList();
Tested and this works in a .Net 3.5 project with a Newtonsoft.Json package suitable for the .Net
Here is a quick solution:
var deserialized = JsonConvert.DeserializeObject<JObject>(json);
var locations = (
from state in deserialized.Properties().Select(v => v.Value).OfType<JObject>()
from city in state.Properties().Select(v => v.Value).OfType<JArray>()
from location in city
select new Location
{
Name = location.Value<string>("Name"),
Address = location.Value<string>("Address"),
City = location.Value<string>("City"),
State = location.Value<string>("State"),
Zip = location.Value<string>("Zip")
}).ToList();
You can use the clases to let newtonsoft resolve what you need
public class Location
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
public class AK
{
public Location[] Anchorage { get; set; }
public Location[] Fairbanks { get; set; }
}
var ak = JsonConvert.DeserializeObject<AK>(json);

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.

Categories

Resources