I have a JSON used as base template which is uploaded in a web platform by the administrator:
{
"age": 0,
"name": "string",
"interest": "string",
"address": "string",
"personalId": 0
}
Then users can create their own JSON schema based on the base template and upload them. These JSON files are all different by each other, but they have in common all the fields in the base template they are derived. The fields can also be in a different order.
In example:
{
"age": 23,
"weight":65,
"name": "Emily",
"gender":"Female",
"interest": "graphic design",
"address": "Elm street",
"personalId": 916742
}
...another:
{
"age": 39,
"name": "John",
"weight": 77,
"interest": "graphic design",
"address": "Elm street",
"gender": "Male",
"personalId": 916742,
"education": "University",
"children": [{
"name": "Katie",
"gender": "Female"
}, {
"name": "Greg",
"gender": "Male"
}]
"someOtherInfo": "lorem ipsum"
}
what I'm trying to do is to remove, from each of the JSON I will receive, all the field which are not present in the base template.
In example from the first entry I will have:
{
"age": 23,
"name": "Emily",
"interest": "graphic design",
"address": "Elm street",
"personalId": 916742
}
The number of fields in the JSON can reach also 300~400 different fields, and the base template contains ~200 fields.
The fields of the base template are all at the first level, no nested fields, and, as I've stored in a database table I could have them also as a list of strings.
Can be achieved using a dynamic object in an efficient way?
Deserialize the json to a class with the variables you are interested in. Anything not part of the class will be ignored
public class Rootobject
{
[JsonProperty("age")]
public int Age { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("interest")]
public string Interest { get; set; }
[JsonProperty("address")]
public string Address { get; set; }
[JsonProperty("personalId")]
public int PersonalId { get; set; }
}
Deserialize to the above class. You dont have to worry about removing anything from the json you are getting. once deserialized to the above class, you have the data you are interested in.
Update
You can use JObject.Parse if you dont want to create a class. You can look up the values (check if they exist as well) and create a new object that you can then save to wherever you need.
var obj = JObject.Parse(json);
dynamic objectToSaveToDB = new ExpandoObject();
objectToSaveToDB.age = obj.GetValue("age");
objectToSaveToDB.name = obj.GetValue("name");
objectToSaveToDB.interest = obj.GetValue("interest");
objectToSaveToDB.address = obj["address"].ToString();
objectToSaveToDB.personalId = obj["personalId"].ToString();
// String version would be JsonConvert.SerializeObject(objectToSaveToDB);
Related
I have a large json file and only want to use certain nested properties, here is the file
{
"type": "champion",
"format": "standAloneComplex",
"version": "6.24.1",
"data": {
"Aatrox": {
"version": "6.24.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade",
"blurb": "Aatrox is a legendary warrior, one of only five that remain of an ancient race known as
the Darkin. He wields his massive blade with grace and poise, slicing through legions in a style
that is hypnotic to behold. With each foe felled, Aatrox's ...",
"info": {
"attack": 8,
"defense": 4,
"magic": 3,
"difficulty": 4
},
"image": {
"full": "Aatrox.png",
"sprite": "champion0.png",
"group": "champion",
"x": 0,
"y": 0,
"w": 48,
"h": 48
},
"tags": [
"Fighter",
"Tank"
],
},
"Ahri": {
"version": "6.24.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox",
"blurb": "Unlike other foxes that roamed the woods of southern Ionia, Ahri had always felt a
strange connection to the magical world around her; a connection that was somehow incomplete.
Deep inside, she felt the skin she had been born into was an ill fit for ...",
"info": {
"attack": 3,
"defense": 4,
"magic": 8,
"difficulty": 5
},
"image": {
"full": "Ahri.png",
"sprite": "champion0.png",
"group": "champion",
"x": 48,
"y": 0,
"w": 48,
"h": 48
},
"tags": [
"Mage",
"Assassin"
],
},
It is a very long json file. I have a class that is
public class Champion
{
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set;}
}
public class ChampionRoot
{
public Dictionary<string, Champion> champions { get; set; }
}
What I am trying to do is start at the properties inside "Data" and only get "id", "key","name" and "title", and Deserialize those properties into my ChampionRoot class. I have searched and tried many things and cannot get it to work. Here is some of what I've tried in my controller
public IActionResult Champions()
{
var url = #"url.......";
WebClient client = new WebClient();
var download = client.DownloadString(url);
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(download);
return Json(champions); //This returns null in the view
}
I have also tried using JObject a few different ways and that doesn't work for me either
JObject obj = JObject.Parse(download);
var json = obj["key"]["id"]["name"]["title"]; //throws object reference error
Then I've tried this
JObject obj = JObject.Parse(download);
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(obj.ToString());
//This also returns null in the view
I have searched and read many answers but I cannot figure it out. The question is how can I only Deserialize those 4 nested properties into an object? The url is http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/champion.json for full json file.
You can use Dictionary<string, Champion> for data property:
public class ChampionRoot
{
public Dictionary<string,Champion> data { get; set; }
}
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(download);
This question already has answers here:
Deserializing JSON Object Array with Json.net
(6 answers)
Closed 4 years ago.
I am new on json in C#. I use newtonsoft.json
I have a json file with data (array):
[
{
"firstName": "Joyce",
"lastName": "Huff",
"isActive": true,
"age": 59,
"gender": "female",
"eyeColor": "green",
"friends": [
"Kendra Buck"
]
},
{
"firstName": "Diann",
"lastName": "Patrick",
"isActive": true,
"age": 45,
"gender": "female",
"eyeColor": "blue",
"friends": [
"Roach Mills",
"Diaz Pickett"
]
},
{
"firstName": "Holt",
"lastName": "Erickson",
"isActive": false,
"age": 53,
"gender": "male",
"eyeColor": "brown",
"friends": [
"Lindsay Wyatt",
"Freeman Mcfadden",
"Matilda Franklin"
]
},
{
"firstName": "Crystal",
"lastName": "Santiago",
"isActive": false,
"age": 31,
"gender": "female",
"eyeColor": "brown",
"friends": [
"Stacy Joseph"
]
}
]
How to I read a json file containing array with C# and perform LINQ query on it? I found example on JObject to read json from file but I could not figure it out how do I handle json array. After reading json array, I would like to run query like: select count(*) from person where age>40;
Please suggest me. Thank you in advance.
Define model:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public bool isActive { get; set; }
public int age { get; set; }
public string gender { get; set; }
public string eyeColor { get; set; }
public List<string> friends { get; set; }
}
Read and deserialize JSON:
string json = System.IO.File.ReadAllText("test.json");
var people = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Person>>(json);
Perform LINQ query:
var peopleOverForty = from p in people
where p.age > 40
select p;
I would suggest creating a Class for the Object you're trying to read, if possible at least.
Then I would deserialize the JSON String to an List<T>where T euqals your Modelclass.
List<YourObject> deserializedObject = JsonConvert.DeserializeObject<YourObject>(jsonString);
Wit this list you can then easily perform LINQ queries like
List<YourObject> selectedObjects = deserializedObject.Where(x => x.age > 31);
This gives you the object selectedObjects with only containing Objects where age > 31.
Please i am new to C# and entity framework, I am working on a projects using web api. I also use postman to test my data and validate them before inserting to database.
My controller Create will accept a json shown below. The JSON object is mapped to my person model, Assets element of the json is a collection from asset model. what i want to do is retrieve all the asset name in the json and check whether they exist in the asset table. if they exist, get the IDs of the asset and save them all to "PersonAsset" table.
NOTE that "PersonAsset" contains "PersonID" & "AssetId"
I have spent over 24 hours trying to solve this problem, i need help please
{
"Id": 0,
"FirstName": "stringFine",
"MiddleName": "test-Sesan",
"LastName": "stringOkay",
"Gender": "Male",
"DateOfBirth": "10-10-2017",
"BirthCertificate": 0,
"Asset": 0,
"WorkTypeId": 2,
"DwellingId": 2,
"HouseholdRoleId": 2,
"HealthFacility": 1,
"Relationship": "string",
"Education": 0,
"MaritalStatusId": 2,
"MobileNumber": "080099813501",
"SettlementTypeId": 2,
"CommunityId": 3,
"SocialGroup": 0,
"Address": "string",
"IsInSchool": 0,
"ReferenceNumber": "100/NSIO/NSR/345660",
"DateInterviewed": "10-10-2017",
"IsActive": true,
"Assets": [
{
"Name": "Testing"
}
],
"SocialGroups": [
{
"Name": "string"
}
]
}
[ResponseType(typeof(PersonModel))]
[ModelValidator]
[HttpPost]
public IHttpActionResult Create(PersonModel model)
{
try
{
var person = Factory.Persons.Create(model);
Service.Persons.Insert(person);
person = Service.Persons.Get(person.Id);
var dto = Factory.Persons.Create(person);
return CreatedAtRoute("DefaultApi", new { id = dto.Id },dto);
}
catch(dbexception){}
How do i accept the values in below JSON and use it in my controller endpoint
"Assets": [
{
"Name": "Testing"
}
],
What does your PersonModel look like? See if the code below helps.
Create Asset model
public class Asset
{
public string Name { get; set; }
}
and then in PersonModel
public class PersonModel
{
public List<Asset> Assets { get; set; }
}
I'm currently working with the following json structure and I'm not sure how to model it on my classes, since I've never run into this kind of structure before. Would appreciate any leads or help:
{ "messages": { "1": { "tid": "309", "status": "0", "timestamp": "1379795079", "uid": "1111111111", "txt": "sometext" }, "2": { "tid": "310", "status": "0", "timestamp": "1379795523", "uid": "2222222222", "txt": "sometext2" } }, "status": 1 }
The messages value objects are not a common json structure that i know of, I understand that these are objects, but I don't know how to map them with my classes.
I Use json2csharp, to model my objects for me. Consider the following json object:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }]
}
I get these objects from the tool:
public class Employee
{
public string firstName { get; set; }
public string lastName { get; set; }
}
public class RootObject
{
public List<Employee> employees { get; set; }
}
Source: http://json2csharp.com/
Technically, your json object is a dictionary, associative array or even hash-table (select appropriate for your target language). Such a data structure is a perfectly reasonable thing to serialize.
However, that particular object would probably have been better serialized as something like:
{ "messages":
[
{ "tid": "309"
, "status": "0"
, "timestamp": "1379795079"
, "uid": "1111111111"
, "txt": "sometext"
}
,
{ "tid": "310"
, "status": "0"
, "timestamp": "1379795523"
, "uid": "2222222222"
, "txt": "sometext2" }
}
]
, "status": 1
}
(unless the sender wanted the option of sending the individual messages items out of order). That's certainly how I would represent it.
This is how I've solved it:
public class MessagesResponse
{
[JsonProperty("messages")]
public Dictionary Messages { get; set; }
[JsonProperty("status")]
public int Status { get; set; }
}
THanks to #rici, I've realized that the use of a dictionary would solve the problem
How do I parse this JSON? I dont know how to define this structure:
[
[{
"timestamp": 1324374926
}],
[{
"id": "9",
"neme": "qqq"
}, {
"id": "19",
"neme": "qqq"
}, {
"id": "29",
"neme": "qqq"
}]
]
JSON parsing code:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Categor[]));
Categor[] result = (Categor[])serializer.ReadObject(responseStream);
by defining data contracts...
Compiler is returning:
System.InvalidCastException: InvalidCastException at
System.Runtime.Serialization.Json.DataContractJsonSerializer.ConvertObjectToDataContract(DataContract
contract, Object value, XmlObjectSerializerReadContextComplexJson
context) at
System.Runtime.Serialization.Json.ObjectToDataContractConverter.ConvertICollectionToCollectionDataContract(DataContractJsonSerializer
serializer, CollectionDataContract contract, Object deserializedValue,
XmlObjectSerializerReadContextComplexJson context) at
System.Runtime.Serialization.Json.DataContractJsonSerializer.ConvertObjectToDataContract(DataContract
contract, Object value, XmlObjectSerializerReadContextComplexJson
context) at System.Runtime.Serializati
How do I parse this JSON?
Matter is that for normal JSON I am creating fe:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Categor[]));
Categor[] result = (Categor[])serializer.ReadObject(responseStream);
[
{
"category": "A",
"subcategories": [
{
"id": "QW",
"name": "A",
"ranking": 100,
"isVisible": true
},
{
"id": "QWN0d",
"name": "Pol",
"ranking": 101,
"isVisible": false
},
...
The data model is:
[DataContract]
public class Articlesubcat
{
[DataMember(Name = "id")]
public string id { get; set; }
[DataMember(Name = "name")]
public string name { get; set; }
[DataMember(Name = "ranking")]
public string ranking { get; set; }
[DataMember(Name = "isVisible")]
public string isVisible { get; set; }
}
[DataContract]
public class Categor
{
[DataMember(Name = "category")]
public string category { get; set; }
[DataMember(Name = "subcategories")]
public List<Articlesubcat> subcat { get; set; }
}
But in this JSON aparently I have:
[
[
{
"timestamp": 1324374926
}
],
[
{
"id": "9",
"neme": "qqq"
},
{
"id": "19",
"neme": "qqq"
},
{
"id": "29",
"neme": "qqq"
}
]
]
and as i see i don't know how to prepair model for this 2 object (array objects) or i don't even know what is name of this structure.
Even though you don't show us the declaration of Categor, Categor[] cannot be the correct root type of your JSON data.
The JSON data is an array of array of something. So your root data type needs to be something like Categor[][].
Update:
Thanks for posting the declaration of Categor. It's now clear that your JSON sample is not an array of Categor instances. Instead, it's an array of two elements. The first one is an array of some unknow object types. It contains a property called timestamp. So it cannot be a Categor instance. The second element is an array of Categor instances (and probably the part you are expecting).
With some luck, you can parse the JSON with the root type Categor[][] and then just use the second element of the outmost array. If that doesn't work, you'll probably have to switch to an alternative JSON library since DataContractJsonSerializer has some limitations with arrays of mixed types.