Using json.net, I've created a json string which is a serialized version of my data table, and am able to deserialize it back to a data table. Let's say my serialized text looks like this:
[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al#test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" } ]
What I'd like to do is add some text to the beginning before the [, or to the end after the ], which would be included in the json text and not hinder the deserialization back to a data table.
I'm using the serialize command, sometimes with a class object as the second (optional) parameter of the serialization command, sometimes not. If I use the second argument, it results in a much more verbose json, which includes table and column definition information.
Either way, I want to possibly add a segment in the json text which will indicate success or failure of the lookup, but will not cause the deserialization to break.
Can anybody suggest a json.net method to do this?
Thanks...
public class Users
{
public string username { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
}
dynamic usercollectionWrapper = new
{
userList = new List<Users>
{
new Users()
{
username= "alan", firstName= "Alan", lastName= "Johnson", email= "alan#test.com"
},
new Users()
{
username= "allison", firstName= "Allison", lastName= "House", email= "al#test.com"
},
new Users()
{
username= "ryan", firstName= "Ryan", lastName= "Carson", email= "ryan#test.com"
}
}
};
var output = JsonConvert.SerializeObject(usercollectionWrapper);
Fiddle:https://dotnetfiddle.net/aAZ3Ah
Update:
public class Users
{
public string username { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
}
public class RootUsers
{
public string status { get; set; }
public List<Users> data { get; set; }
}
dynamic usercollectionWrapper = new
{
add = new RootUsers()
{
status = "success",
data = new List<Users>
{
new Users()
{
username= "alan", firstName= "Alan", lastName= "Johnson", email= "alan#test.com"
},
new Users()
{
username= "allison", firstName= "Allison", lastName= "House", email= "al#test.com"
},
new Users()
{
username= "ryan", firstName= "Ryan", lastName= "Carson", email= "ryan#test.com"
}
}
}
};
var output = JsonConvert.SerializeObject(usercollectionWrapper);
Fiddle:https://dotnetfiddle.net/Ic6M1Z
Related
I'm trying to get all the points within a distance of 10 meter for example. the Withindistance() doesn't work and it doesn't give me any error so i don't know what is the issue.
Here is my controller :
public IActionResult GetWeather()
{
IList<WeatherViewModel> Tags = new List<WeatherViewModel>();
var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
var searchAreaCoordinate = new NetTopologySuite.Geometries.Coordinate(-1.88049067645237,52.486034913778894);
var searchArea = geometryFactory.CreatePoint(searchAreaCoordinate);
Root weather = JsonConvert.DeserializeObject<Root>(System.IO.File.ReadAllText(#"C:\local\weather.json"));
var features = (from c in weather.features select c)
.Select(x=> new {x.id,x.type,x.geometry.coordinates,Coor= new Point(x.geometry.coordinates[0],x.geometry.coordinates[1]){ SRID = 4326 },
})
.Where(x=>x.Coor.IsWithinDistance(searchArea, 10))
.ToList();
;
foreach (var item in features)
{
Tags.Add(new WeatherViewModel()
{
id = item.id,
type = item.type,
Long = item.coordinates[0],
Lat = item.coordinates[1],
test = item.Coor.ToString(),
Distance = item.Coor.Distance(searchArea)
// WKT = item.z
// WKT = new NetTopologySuite.Geometries.Coordinate( item.coordinates[0] , item.coordinates[1])
}
);
}
return View(Tags);
}
}
Note that I'm getting all the records . The Where() doesn't work so if i comment it out ill still get all the results:
Json Class
public class Root
{
public string type { get; set; }
public ParameterDescription parameter_description { get; set; }
public List<double> bbox { get; set; }
public List<Feature> features { get; set; }
}
public class Geometry
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class Feature
{
public string id { get; set; }
public string type { get; set; }
public Properties properties { get; set; }
public Geometry geometry { get; set; }
public Geometry Coor {get;set;}
}
Json sample
{
"type": "FeatureCollection",
"features": [
{
"id": "1",
"type": "Feature",
"properties": {
"t": [
1,
],
"s": [
1,
],
"Time": [
"2021-11-01",
]
},
"geometry": {
"type": "Point",
"coordinates": [
-1.881,
52.486
]
}
},
]
}
Any idea?
{
"value": [{
"odata.type": "SP.User",
"odata.id": "https://www.test.com/_api/Web/GetUserById(37)",
"odata.editLink": "Web/GetUserById(37)",
"Id": 37,
"IsHiddenInUI": false,
"LoginName": "i:0#.w|domain\\jos",
"Title": "Mr joseph",
"PrincipalType": 1,
"Email": "joe#yopmail.com",
"IsEmailAuthenticationGuestUser": false,
"IsShareByEmailGuestUser": false,
"IsSiteAdmin": false,
"UserId": {
"NameId": "s-1-5-21-2613750078-2161710047-3166685486-1473",
"NameIdIssuer": "urn:office:idp:activedirectory"
}
}, {
"odata.type": "SP.User",
"odata.id": "https://www.test.com/_api/Web/GetUserById(90)",
"odata.editLink": "Web/GetUserById(90)",
"Id": 90,
"IsHiddenInUI": false,
"LoginName": "i:0#.w|domain\\pam",
"Title": "anthony",
"PrincipalType": 1,
"Email": "anthony#yopmail.com",
"IsEmailAuthenticationGuestUser": false,
"IsShareByEmailGuestUser": false,
"IsSiteAdmin": false,
"UserId": {
"NameId": "s-1-5-21-2613750078-2161710047-3166685486-1437",
"NameIdIssuer": "urn:office:idp:activedirectory"
}
}
}
after deserializing this JSON I want to get the Title based on the Id so lets say if the Id = 37 I want to return a string that contain Mr joseph. is it possible to do this using LINQ? thank you for your help in advance...
I am desiralizing to this class:
public class UsersInformationValue
{
[JsonProperty("odata.type")]
public string Odata_Type { get; set; }
[JsonProperty("odata.id")]
public string Odata_Id { get; set; }
[JsonProperty("odata.editlink")]
public string Odata_EditLink { get; set; }
public int Id { get; set; }
public bool IsHiddenInUI { get; set; }
public string LoginName { get; set; }
public string Title { get; set; }
public int PrincipalType { get; set; }
public string Email { get; set; }
public bool IsEmailAuthenticationGuestUser { get; set; }
public bool IsShareByEmailGuestUser { get; set; }
public bool IsSiteAdmin { get; set; }
public UserIdDetails UserId { get; set; }
}
You can do that easily with a projection.
var title = values.Where(v => v.Id == 37).Select(v => v.Title).FirstOrDefault();
var title = values.FirstOrDefault(v => v.Id == 37)?.Title;
I'm using asp.Net Core (EF/MVC) and consuming an API through httpRequestMessage StringContent.
How can I do for serialize multiples Models classes/View models into a single Json (Newtonsoft.Json), like the exemple below?
I will really appreciate some code exemple or anything else...
{
"seller_id": "6eb2412c-165a-41cd-b1d9-76c575d70a28",
"amount": 100,
"order": {
"order_id": "6d2e4380-d8a3-4ccb-9138-c289182818a3",
"product_type": "service"
},
"customer": {
"customer_id": "customer_21081826",
"email": "customer#email.com.br",
"billing_address": {
"street": "Av. Brasil",
"number": "1000",
"city": "Porto Alegre",
"state": "RS",
"postal_code": "90230060"
}
},
"device": {
"ip_address": "127.0.0.1",
"device_id": "hash-device-id"
}
}
Create models like below:
public class RootoClass
{
public Guid Seller_id { get; set; }
public int Amount { get; set; }
public Order Order { get; set; }
public Customer Customer { get; set; }
public Device Device { get; set; }
}
public class Order
{
public Guid Order_id { get; set; }
public string Product_type { get; set; }
}
public class Customer
{
public string Customer_id { get; set; }
public string Email { get; set; }
public Billing_Address Billing_address { get; set; }
}
public class Billing_Address
{
public string Street { get; set; }
public string Number { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal_code { get; set; }
}
public class Device
{
public string Ip_address { get; set; }
public string Device_id { get; set; }
}
Using Newtonsoft.Json.JsonConvert:
public string Index()
{
var model = new RootoClass()
{
Seller_id = new Guid("6eb2412c-165a-41cd-b1d9-76c575d70a28"),
Amount = 100,
Order = new Order()
{
Order_id = new Guid("6d2e4380-d8a3-4ccb-9138-c289182818a3"),
Product_type = "service"
},
Customer = new Customer()
{
Customer_id = "customer_21081826",
Email = "customer#email.com.br",
Billing_address = new Billing_Address()
{
Street = "Brasil",
Number = "1000",
City = "Porto Alegre",
State = "RS",
Postal_code= "90230060"
}
},
Device = new Device()
{
Ip_address= "127.0.0.1",
Device_id= "hash-device-id"
}
};
var json = JsonConvert.SerializeObject(model);
return json;
}
I am creating a rest api in spring boot as well as in jersey. I need to pass a nested JSON structure as request. I have no idea how to do it.
The nested structure is below,
{
"student": "",
"groupId": "a1",
"standard": "Fifth",
"isPassed": true,
"section": "A",
"data": {
"name": "Abcd",
"age": "11"
},
"additional": {
"Personal": {
"1": {
"address": {
"Home": [
"xys"
],
"Permanent": [
"xyz"
],
"Language": [
"English",
"French"
]
},
"street": "5",
"Mother": null,
"Father": null
}
}
"state": "xyz",
"Sibblings": true
}
}
I am expecting the rest call to accept this structure.
You can try something like this, first create request dto which will map the json to the DTO
import java.util.List;
public class RequestDTO {
private String student;
private String groupId;
private String standard;
private Boolean isPassed;
private String section;
private UserData data;
private Additional additional;
public String getStudent() {
return student;
}
public void setStudent(String student) {
this.student = student;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
public Boolean getPassed() {
return isPassed;
}
public void setPassed(Boolean passed) {
isPassed = passed;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public UserData getData() {
return data;
}
public void setData(UserData data) {
this.data = data;
}
public Additional getAdditional() {
return additional;
}
public void setAdditional(Additional additional) {
this.additional = additional;
}
}
class UserData {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Additional{
private Personal personal;
private String state;
private Boolean Sibblings;
public Personal getPersonal() {
return personal;
}
public void setPersonal(Personal personal) {
this.personal = personal;
}
}
class Personal{
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
class Address{
private List<String> Home;
private List<String> Permanent;
private List<Language> Language;
public List<String> getHome() {
return Home;
}
public void setHome(List<String> home) {
Home = home;
}
}
enum Language{
English,French;
}
Second create a API handler which will accept this request
#RestController
#RequestMapping("/api")
public class AdminController {
#RequestMapping(value = "/test", method = RequestMethod.POST)
public RequestDTO postData(#RequestBody RequestDTO requestDTO) {
logger.info("Body---->", requestDTO);
return requestDTO;
}
}
You can test it via below curl
curl -X POST \
http://localhost:<PORT>/<context>/api/test \
-H 'Content-Type: application/json' \
-H 'Postman-Token: 7b66a9cf-8b69-4555-9bb2-1c186bff368d' \
-H 'cache-control: no-cache' \
-d '{
"student": "",
"groupId": "a1",
"standard": "Fifth",
"isPassed": true,
"section": "A",
"data": {
"name": "Abcd",
"age": "11"
},
"additional": {
"Personal": {
"address": {
"Home": [
"xys"
],
"Permanent": [
"xyz"
],
"Language": [
"English",
"French"
]
},
"street": "5",
"Mother": null,
"Father": null
},
"state": "xyz",
"Sibblings": true
}
}'
I will suggest you to go though offical docs for better understanding
class Data
{
private String name;
private Integer age;
}
class Student{
private String student;
private String groupId;
private String standard;
private Boolean isPassed;
private String section;
private Data data;
private Additional additional;
}
Here is something to get started with. Further nesting has to be done the similar way
My Coding is like below,i have given the output which now i am getting and the expected output which i want, please go through it.
public List<CompanyDto> GetCompanyData()
{
List<CompanyDto> resultCompanyDtoViews = new List<CompanyDto>();
var viewCompanyDtoData = db.ds_CompanyDto.AsQueryable().AsNoTracking().ToList();
var companyDtoData = viewCompanyDtoData .Select(a => new CompanyDto()
{
Id = a.Id,
CompanyId=a.CompanyId,
CompanyName=a.CompanyName,
}).GroupBy(a => a.CompanyId).Select(a => a.First()).ToList();
foreach (var companyData in companyDtoData)
{
CompanyDto companyDto = new CompanyDto();
companyDto.Id = companyData.Id;
companyDto.CompanyId=companyData.CompanyId;
companyDto=companyData.CompanyName
companyDto.countries =
viewCompanyDtoData.Where(a => a.CompanyId == companyData.CompanyId).Select(a => new CountryDto()
{
Country = a.Country
}).ToList();
resultCompanyDtoViews.Add(companyDto);
}
return resultCompanyDtoViews;
}
-----------------------------------Coding in DTO class
public class CompanyDto
{
[Key]
public Nullable<long> Id { get; set; }
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public List<CountryDto> countries { get; set; }
}
public class CountryDto
{
public string Country { get; set; }
}
----------------------Out put Now getting
{
"value": [
{
"Id": 1,
"CompanyId": 1,
"CompanyName": "TCS",
"countries": [
{
"Country": "3st Country"
},
{
"Country": "4st Country"
},
{
"Country": "6st Country"
}
]
}
]
}
--------------------------Expected Output
{
"value": [
{
"Id": 1,
"CompanyId": 1,
"CompanyName": "TCS",
"countries": [
"3st Country",
"4st Country",
"6st Country"
]
}
]
}
Please help me out on this
my expected json should be like the last expected json one , please help me hoe to achieve this result