RealmJson.Extensions - How to import entire JSOn? - json

I am using https://github.com/sushihangover/Realm.Json.Extensions to import a JSON into my realm database. However, only the top level object is created but not all nested objects in the JSON.
Below an example. Imagine three classes: A, B and C. A containing B and B containing C.
public class A : RealmObject
{
[PrimaryKey]
public string Id { get; set; } = Guid.NewGuid().ToString();
[Backlink(nameof(B.A))]
public IQueryable<B> BList { get; }
}
public class B : RealmObject
{
[PrimaryKey]
public string Id { get; set; } = Guid.NewGuid().ToString();
public A A { get; set; }
[Backlink(nameof(C.B))]
public IQueryable<C> CList { get; }
}
public class C : RealmObject
{
[PrimaryKey]
public string Id { get; set; } = Guid.NewGuid().ToString();
public B B { get; set; }
}
When I export my database to json I get the following:
{
"$id": "1",
"Id": "979e7341-0d16-4ba4-b91b-31ec81bb18ad",
"BList": [
{
"$id": "2",
"Id": "dbb35317-eae0-4978-9675-e0246805fc34",
"CList": [
{
"$id": "3",
"Id": "2da5ac92-bc73-4f80-8a27-051bbf4e5e66",
},
{
"$id": "4",
"Id": "a40f7f12-7eee-47ee-845f-4481b72c0109",
},
{
"$id": "5",
"Id": "37606fc1-74a0-4a9e-a802-587076429edc",
}
]
}
]
}
However, when I call:
using (var r = Realm.GetInstance()) {
var s = r.CreateObjectFromJson<A>(json);
}
Only the parent object A is created without any of the children (1 B object and 3 C objects).
Any suggestions?

Related

stream writer is not writing to JSON file in webapi

Im trying to write data in a JSON file using webapi but stream writer is not writing data to the file.
JSON File :
{
"Students": [
{
"id": 1,
"name": "Ravi",
"department": "IT"
},
{
"id": 2,
"name": "Raj",
"department": "hr"
},
{
"id": 3,
"name": "avi",
"department": "it"
},
{
"id": 4,
"name": "rome",
"department": "HR"
},
{
"id":5,
"name": "virat",
"department": "HR"
},
{
"id":6 ,
"name": "Tushar",
"department": "RM"
}
]
}
Class
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
public class Students
{
public List<Student> students { get; set; }
}
Api controller: [HttpPost] method for writing data to the json file.
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
[HttpPost]
public IActionResult Add(Students _Student)
{
using (var fs = new FileStream("C:/Users/tanmay_pawar/source/repos/CRUDAPI/CRUDAPI/people.json", FileMode.Append))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(_Student);
}
}
The data recieved in by _Student is not getting added to the json file.
try this
public IActionResult Add(Students _Student)
{
if(_Student==null || _Student.students==null) return null;
var filePath = #"C:\Users\....\..json";
var json = File.ReadAllText(filePath);
Students students = JsonConvert.DeserializeObject<Students>(json);
students.students.AddRange(_Student.students);
json=JsonConvert.SerializeObject(students);
File.WriteAllText(filePath, json);
}
Try the code like below:
[HttpPost]
public IActionResult Add(Students _Student)
{
string jsonresult = JsonConvert.SerializeObject(_Student);
string path = #"C:\c\people.json";
using(var tw=new StreamWriter(path,true))
{
tw.WriteLine(jsonresult.ToString());
tw.Close();
}
return Ok();
}
result:
Update more picture, add data inside the existing JSON file.

How to delete Json particular element in C#?

public class students
{
public int ID { get; set; }
public string fName { get; set; }
public string mName { get; set; }
public string lName { get; set; }
public string Dept { get; set; }
public string Degree { get; set; }
public _Semister[] ComplitedSemister { get; set; }
public string SemesterCode { get; set; }
public string Year { get; set; }
}
public class _Semister
{
public int Id { get; set; }
public string Name { get; set; }
public string Instructor { get; set; }
public int Credit { get; set; }
}
This is My student class
[
{
"ID": 101,
"fName": "Kamal",
"mName": "Faheem",
"lName": "Khabib",
"Dept": "CSE",
"Degree": "BSC",
"ComplitedSemister": [
{
"Id": 2001,
"Name": "OOP",
"Instructor": "Jamal",
"Credit": 2354
}
],
"SemesterCode": "Summer",
"Year": "2014"
},
{
"ID": 454,
"fName": "fdgfdg",
"mName": "sgdfsd",
"lName": "sdfgg",
"Dept": "fdgsdf",
"Degree": "sfdgdf",
"ComplitedSemister": [
{
"Id": 324,
"Name": "cgbf",
"Instructor": "dgfd",
"Credit": 54
}
],
"SemesterCode": "Ummer",
"Year": "3423"
}
]
This is my Json File. I want to delete all element for a particular ID. For example, for ID = 101 I want delete whole data for this ID. SO the next ID = 454 become the first student in json file. But I can't Delete . SO how can I delete ?
You can do it by 2 ways ( I am using Newtonsoft.Json. You can install it by Nuget)
Parse Json to a JArray. Remove item from array. Serialize the JArray.
//your json
var json="[{\"ID\":101,\"fName\":\"Kamal\",\"mName\":\"Faheem\",\"lName\":\"Khabib\",\"Dept\":\"CSE\",\"Degree\":\"BSC\",\"ComplitedSemister\":[{\"Id\":2001,\"Name\":\"OOP\",\"Instructor\":\"Jamal\",\"Credit\":2354}],\"SemesterCode\":\"Summer\",\"Year\":\"2014\"},{\"ID\":454,\"fName\":\"fdgfdg\",\"mName\":\"sgdfsd\",\"lName\":\"sdfgg\",\"Dept\":\"fdgsdf\",\"Degree\":\"sfdgdf\",\"ComplitedSemister\":[{\"Id\":324,\"Name\":\"cgbf\",\"Instructor\":\"dgfd\",\"Credit\":54}],\"SemesterCode\":\"Ummer\",\"Year\":\"3423\"}]";
var jArray=JArray.Parse(json);
var itemToRemove = (JToken) jArray.Where(a => (int) a["ID"]==101).First();
jArray.Remove(itemToRemove);
json=jArray.ToString();
Deserialize JSON to strongly-typed list of items. Remove item from list. Serialize the list.
var json= ...your json..;
var jDeserialized= JsonConvert.DeserializeObject<List<students>>(json);
var removeItem=jDeserialized.Where(d =>d.Id==101 ).First();
jDeserialized.Remove(removeItem);
json=JsonConvert.SerializeObject (jDeserialized, Newtonsoft.Json.Formatting.Indented);
result json
[
{
"ID": 454,
"fName": "fdgfdg",
"mName": "sgdfsd",
"lName": "sdfgg",
"Dept": "fdgsdf",
"Degree": "sfdgdf",
"ComplitedSemister": [
{
"Id": 324,
"Name": "cgbf",
"Instructor": "dgfd",
"Credit": 54
}
],
"SemesterCode": "Ummer",
"Year": 3423
}
]

How to extract only part of the JSON and de-serialize it in .netcore

I have .net core application , where an API is called through HTTPClient.
The response for that API in JSON format is as follows:
{
"ID": 25,
"Customer": "CustomerName",
"total": 100,
"details": [
{
"ItemId": "Item1",
"ItemName": "Name1",
"Price": "10"
},
{
"ItemId": "Item2",
"ItemName": "Name2",
"Price": "50"
},
{
"ItemId": "Item3",
"ItemName": "Name3",
"Price": "40"
}
]
}
I get this response from -- > var response = client.GetAsync(ApiPath).Result;
Now from the response variable I need details only for details like :
{
{
"ItemId": "Item1",
"Price": "10"
},
{
"ItemId": "Item2",
"Price": "50"
},
{
"ItemId": "Item3",
"Price": "40"
}
}
I have a DTO class like this :
public class ItemDetails
{
public string ItemId { get; set; }
public string Price { get; set; }
}
Can anyone help in extracting the details according to the DTO class from the main variable "response".
Many thanks!
Try this if you are using newtonsoft
var token = JObject.Parse(response);//load
var detailsToken = token.SelectToken("details");//select
var itemDetails = detailsToken.ToObject<ItemDetails[]>(); //cast to array
Only the properties that exist on ItemDetails will be mapped
You can deserialize the response into an object and take whatever you like from it.
Use the built-in JSON library in .net-core as following
using System.Text.Json;
using System.Text.Json.Serialization;
then make a Response classes to contain the Response values
public class ResponseObject
{
public int ID { get; set; }
public string Customer { get; set; }
[JsonPropertyName("total")]
public int Total { get; set; }
[JsonPropertyName("details")]
public ItemDetails[] Details { get; set; }
}
public class ItemDetails
{
public string ItemId { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
}
finally, deserialize and extract whatever you like as following
var o = JsonSerializer.Deserialize<ResponseObject>(response);
ItemDetails[] itemDetails= o.Details;

ASP.NET Core 5 returning JSON adding $id and $values properties

I'm using ASP.NET Core 5. As below, I'm using System.Text.Json:
public IActionResult Index()
{
var result = GetAllMenuItems();
return Ok(result);
}
The expected shape of my JSON is:
[
{
"NameEn": "omlet en",
"MenuId": 258,
"Categories": [
{
"MenuCategoryEn": "Lunch En",
"Id": 175
},
{
"MenuCategoryEn": "Dinner En",
"Id": 176
}
],
"Id": 213
}
]
But it is generating $id with random number and wrapping an actual data within $value:
{
$id: "1",
$values: [
{
$id: "2",
nameEn: "omlet en",
menuId: 258,
categories: {
$id: "3",
$values: [
{
$id: "4",
menuCategoryEn: "Lunch En",
id: 175
},
{
$id: "6",
menuCategoryEn: "Dinner En",
id: 176
}
]
},
id: 213
}
]
}
Classes are as follow and contains many to many navigation properties
public class MenuItem : BaseEntity
{
public string NameEn { get; set; }
public long MenuId { get; set; }
public List<MenuCategory> Categories { get; set; } = new();
public Menu Menu { get; set; }
}
public partial class MenuCategory : BaseEntity
{
public string MenuCategoryEn { get; set; }
public List<MenuItem> MenuItems { get; set; } = new();
}
Is there any proper solution to fix this?
Do you configure the JsonOptions in stratup like below?
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
Don't set ReferenceHandler as Preserve if you did that.
options.JsonSerializerOptions.ReferenceHandler = null;
Use this instead
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
Minimal API

How to parse the Json data in WP8?

I'm newbie to windows phone 8 development. I am working on application in which I need parse the Json. please help me with this json data
{
"School": [
{
"info": {
"name": "Dary",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
},
{
"info": {
"name": "Henry",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
}
]
}
this is class
public class Info
{
public string name { get; set; }
public string description { get; set; }
public string startAt { get; set; }
public string endAt { get; set; }
public string status { get; set; }
public int type { get; set; }
}
public class Gui
{
public int size { get; set; }
public string sizeMB { get; set; }
}
public class School
{
public Info info { get; set; }
public Gui gui { get; set; }
}
public class RootObject
{
public List<School> School { get; set; }
}
Thanks in advance.
As Peter Torr suggests, JSON.NET is a great option. There is a DataContractJsonSerializer for serialization in the .net framework, but its not very robust. You can easily add JSON.NET to your project with Nuget. Place your json in a string variable
string json = "<<your json string>>"
or read from a file
string json = File.ReadAllText("<<path to file>>");
Then, the following code will deserialize your text.
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
You can lose the root object (it looks like it came from a javascript to C# converter) if you keep only the json array (the text between the brackets [] ), and then you can deserialize just the array.
List<School> school = JsonConvert.DeserializeObject<List<School>>(json);