Json data reading - json

I have following json format data reading problem
I tried this code which is not working because Answer node have Answer named data
string filePath = Server.MapPath("../App_Data/history.txt");
using (StreamReader r = new StreamReader(filePath))
{
string json = r.ReadToEnd();
List<RootObject> Questions =
JsonConvert.DeserializeObject<List<RootObject>>(json);
public class Answer
{
public string Answer { get; set; }
}
public class Question
{
public string Question { get; set; }
public int CorrectAnswer { get; set; }
public List<Answer> Answers { get; set; }
}
public class RootObject
{
public List<Question> Questions { get; set; }
}
JSON Data :
{
"Questions": [
{
"Question": "Who was the Chola King who brought Ganga from North to South?",
"CorrectAnswer": 1 ,
"Answers": [
{
"Answer": "Raja Raja Chola"
},
{
"Answer": "Rajendra Chola"
},
{
"Answer": "Parantaka"
},
{
"Answer": "Mahendra"
}
]
},
{
"Question": "The writ of 'Habeas Corpus' is issued in the event of:",
"CorrectAnswer": 2 ,
"Answers": [
{
"Answer": "Loss of Property"
},
{
"Answer": "Refund of Excess Taxes"
},
{
"Answer": "Wrongful Police Detention"
},
{
"Answer": "Violation of the Freedom of Speech"
}
]
}
]}

Related

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

Json.net append json file

I have the following code which uses Json.net:
class HistorianRecord
{
public string tagname { get; set; }
public string engunits { get; set; }
public string value { get; set; }
public string quality { get; set; }
public DateTime timestamp { get; set; }
}
private static void createJSONFile(DataTable dt)
{
var HistorianData = new List<HistorianRecord>();
foreach(DataRow row in dt.Rows)
{
HistorianData.Add(new HistorianRecord()
{
tagname = row["tagname"].ToString(),
engunits = row["engunits"].ToString(),
value = row["value"].ToString(),
quality = row["quality"].ToString(),
timestamp = DateTime.Parse(row["timestamp"].ToString())
});
}
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(HistorianData);
var deserializedResult = serializer.Deserialize<List<HistorianRecord>>(serializedResult);
File.WriteAllText(folderPath + fileName, JsonConvert.SerializeObject(deserializedResult));
}
Which produces the following JSON file, which I have shortened for this post as the are > 1000 rows in the datatable:
[
{
"tagname": "mytag1",
"engunits": "",
"value": "2",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:05Z"
},
{
"tagname": "myTag2",
"engunits": "",
"value": "0",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:00Z"
}
]
I would like to amend my code to so I can add some items at the beginning of the JSON file so it looks more like this:
[
{
"name": "ARandomName",
"content": [
{
"tagname": "mytag1",
"engunits": "",
"value": "2",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:05Z"
},
{
"tagname": "myTag2",
"engunits": "",
"value": "0",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:00Z"
}
]
}
]
This is so I can create some documents for a test MongoDB installation that I am investigating so all help is appreciated.
You simply can wrap your deserialized list of HistorianRecords in an anonymous object and reserialize it:
var anon = new
{
name = "ARandomName",
content = deserializedResult
};
string newJson = JsonConvert.SerializeObject(anon, Formatting.Indented);
Fiddle: https://dotnetfiddle.net/6kSvxS

asp.net core 2.1 json serialization null array is not ignored

I have the following classes:
FormGroupModel has a list of FormFieldModel which has a list of FieldOptionModel.
public class FormGroupModel
{
public string GroupLabel { get; set; }
public IEnumerable<FormFieldModel> Fields { get; set; }
}
public class FormFieldModel
{
public string Name { get; set; }
public string Label { get; set; }
public string ControlType { get; set; }
public IEnumerable<FieldOptionModel> Options { get; set; }
}
public class FieldOptionModel
{
public string Value { get; set; }
public string Label { get; set; }
}
I configured Json serializationsettings in Startup.cs to NullValueHandling.Ignore. Null values for my other API return values are all ignored as expected. This object serialization still does not get rid of the Options array when it's empty. I also tried DefaultValueHandling.Ignore but does not work either. How can I get the Options list to be ignored when empty?
[
{
"groupLabel": "Basic Information",
"fields": [
{
"name": "ProjectDescription",
"label": "Project Description",
"controlType": "multiline",
"options": []
},
{
"name": "ProjectId",
"label": "Project Id",
"controlType": "textfield",
"options": []
},
{
"name": "ProjectName",
"label": "Project Name",
"controlType": "textfield",
"options": []
},
{
"name": "ProjectScope",
"label": "Project Scope",
"controlType": "multiline",
"options": []
}

RealmJson.Extensions - How to import entire 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?