Access a dictionary with json-glib-1.0 in Vala? - json

I'm trying to access a json dict with json-glib but I can't figure out how to access it following Valadoc
I'm trying to access files, the dict looks like this:
"items": [
{
"kind": "webfonts#webfont",
"family": "ABeeZee",
"category": "sans-serif",
"variants": [
"regular",
"italic"
],
"subsets": [
"latin"
],
"version": "v12",
"lastModified": "2019-04-29",
"files": {
"regular": "http://fonts.gstatic.com/s/abeezee/v12/esDR31xSG-6AGleN6tKukbcHCpE.ttf",
"italic": "http://fonts.gstatic.com/s/abeezee/v12/esDT31xSG-6AGleN2tCklZUCGpG-GQ.ttf"
}
},
Someone can help?

You can use the deserialization features of GObject:
public class Obj : Object {
public string kind { get; set; }
public string family { get; set; }
public string category { get; set; }
public string[] variants { get; set; }
public int num { get; set; }
public string to_string () {
StringBuilder builder = new StringBuilder ();
builder.append_printf ("kind = %s\n", kind);
builder.append_printf ("family = %s\n", family);
builder.append_printf ("category = %s\n", category);
builder.append_printf(#"variants:[\n");
foreach (var item in variants)
builder.append_printf(#"\t$item\n");
builder.append_printf(#"]\n");
return (owned) builder.str;
}
}
void main (string[] args) {
string data = """
{
"kind" : "my string",
"family" : "ABeeZee",
"category" : "sans-serif",
"variants": [
"regular",
"italic"
]
}""";
var obj = Json.gobject_from_data (typeof (Obj), data) as Obj;
print (#"$obj");
}
This will output:
> vala console.vala --pkg json-glib-1.0
kind = my string
family = ABeeZee
category = sans-serif
variants:[
regular
italic
]

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

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

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?

Creating json object in mvc and returning from controller

I need to create the following in a loop, my has "name" and "id" where name will be used for the value property of the json object and id will be used for the "data" and query will be some string I can set.
I tried using keypair but could not figure out how to do this property. Any help would be appreciated.
{
"query": "Unit",
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
I am trying to return results for this autocomplete widget
https://www.devbridge.com/sourcery/components/jquery-autocomplete/
You can just create an anonymous object. To return the JSON as indicated in your question, it would be
public JsonResult GetCities(string query)
{
var data = new
{
query = "Unit",
suggestions = new[]
{
new { value = "United Arab Emirates", data = "AE" },
new { value = "United Kingdom", data = "UK" },
new { value = "United States", data = "US" }
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
Side note: Unsure of the purpose of the method parameter?
I hate to go full blown on this, but maybe create your own classes?
public class DataValuePair
{
public string Data {get;set;}
public string Value {get;set;}
}
public class SearchResult
{
public string Query {get;set;}
public List<DataValuePair> Suggestions {get;set;}
}
And now you can return a JSON Result
return Json(mySearchResult);
Answer from OP:
Figured it out, below is the code
public ActionResult GetCities(string query)
{
var obj = new CitySuggestion();
obj.suggestions.Add(new Suggestion { value = "test1", data = "test1" });
obj.suggestions.Add(new Suggestion { value = "test2", data = "test2" });
obj.suggestions.Add(new Suggestion { value = "test3", data = "test3" });
return Content(JsonConvert.SerializeObject(obj), "application/json");
}
public class CitySuggestion
{
public CitySuggestion()
{
suggestions = new List<Suggestion>();
}
public List<Suggestion> suggestions
{
get;
set;
}
}
public class Suggestion
{
public string value { get; set; }
public string data { get; set; }
}