Ember Data - Serialization Options - json

I have a model with a hasMany realtionship.
I currently use the EmbeddedRecordsMixin to include the JSONAPI in my payload that is then sent to the server.
My problem is that I wish to send only the JSON representation of this object. i.e without type and attributes hash. Instead I wish to the send the payload as simply JSON { id: 1, Name: 'Darren', Surname: 'Blh' ... }
How is it possible to convert the JSONAPI to JSON?
Thanks
Darren

I solved this by overriding the serialize() method on the serializer.
serialize(snapshot, options) {
var json = this._super(...arguments);
for (let i = 0; i < json.passengers.length; i++ ) {
console.log('Converting Person JSON:API to JSON');
json.passengers[i].id = json.passengers[i].data.id;
json.passengers[i].firstName = json.passengers[i].data.attributes.firstName;
json.passengers[i].lastName = json.passengers[i].data.attributes.lastName;
delete json.passengers[i].data;
}
return json;
}

Related

Net core dapper and postgres jsonb column

I want to POST some custom JSON to my postgres jsonb column via postman using the below request.
The custom part is sent in the "Settings" > "data" node. I don't want to apply the custom part to a model I just want to send in any kind of json and store it.
{
"name": "Test",
"settings": {
"data": {
"customdata": "hello",
"custommore": "bye"
}
}
}
The "data" node is modelled - like this:
public string Data { get; set; } //I have tried JSONDocument and Jsonb types to no avail.
Postman errors with this:
"errors": {
"$.settings.data": [
"The JSON value could not be converted to System.String. Path: $.settings.data | LineNumber: 3 | BytePositionInLine: 17."
]
}
The request doesn't even hit my controller method. I think it is because the customdata and custommore is not mapped to a model.
Is there a way of sending in custom JSON data that is not fixed to a model of any kind - or must it be part of a model?
I'm struggling to find anything about this that doesn't relate to EF core which is not what I am using.
You can use custom model binding,and get json data from HttpContext.Request.Body,and then use sonConvert.DeserializeObject to get json object.You can set the data to the format you want.
Here is a demo:
DataBinder:
public class DataBinder:IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var model1 = new Customer();
using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body))
{
var body = reader.ReadToEndAsync();
var mydata = JsonConvert.DeserializeObject<JObject>(body.Result);
model1.Name = mydata["name"].ToString();
model1.Settings = new Settings
{
Data = mydata["settings"]["data"].ToString()
};
}
bindingContext.Result = ModelBindingResult.Success(model1);
return Task.CompletedTask;
}
}
Controller:
public IActionResult TestCustomModelBinding([ModelBinder(BinderType = typeof(DataBinder))]Customer customer) {
return Ok();
}
result:

Angular 4 - Typescript: json2typescript json key mapper

Sorry but I didn't explain it very well. I edit my question again:
I have an angular 4 application and I use json2typescript to convert from json to object and vice versa but I have a problem because I have a class structure and the response json from an external api has another structure. Example:
Customer {
#JsonProperty('idCardNumber', String)
idCardNumber: string = undefined;
#JsonProperty('rolInfo.name',String)
name: string = undefined;
#JsonProperty('rolInfo.surname',String)
surname: string = undefined;
}
External Json API Reponse:
{
"idCardNumber": "08989765F",
"rolInfo": {
"name": "John"
"surname: "Smith"
}
}
So, I would like to map from the json above to my Customer object and not to change my structure. I tried to put 'rolInfo.name' into the JsonProperty, but that doesn't work.
Change your Customer class to something like below
Customer {
#JsonProperty('idCardNumber', String)
idCardNumber: string = undefined;
#JsonProperty('rolInfo', Any)
rolInfo: any = {}; // if you set this to undefined, handle it in getter/setter
get name(): string {
return this.rolInfo['name'];
}
set name(value: string) {
this.rolInfo['name'] = value;
}
get surname(): string {
return this.rolInfo['surname'];
}
set surname(value: string) {
this.rolInfo['surname'] = value;
}
}
That should do it
Seems like the response JSON is already in a good format and you don’t need to do the conversion.
I would recommend creating models as they allow for serialization and deserialization when making API calls and binding the response to that model.

Deserialize Json Object list with id as root with jackson

I have this json structure from firebase where it's a list of objects but the root of each object is the ID
How can I serialize this to a list of object with the id/root as a member variable. This is for Spring boot so I would prefer if it were a Jackson2 solution.
This may be the same question as Jackson JSON key as value in Java but my answer is better because it doesn't require an extra/useless class
val reader = ObjectMapper().reader()
val tree = reader.readTree(testJson)
val eventList = mutableListOf<Event>()
tree.fields().iterator().forEach {
val event = Event(
it.key,
it.value.get("name").asText(),
it.value.get("description").asText(),
it.value.get("startDate").asText(),
it.value.get("startTime").asText(),
it.value.get("endDate").asText(),
it.value.get("endTime").asText(),
it.value.get("imageUrl").asText()
)
eventList.add(event)
}
I have found a solution using jackson in kotlin, it's not the prettiest but it works. the fields method returns a map of children. So, I am iterating through the map and adding the key as the object id member and then grabbing the rest of the data from the nested map.
Sorry, I am not a pro in Jackson. But there is a simple way to transform your object in JavaScript -- and perhaps this will lay the foundation for something that can be ported to Jackson (java?)
This is the convertData function that does the transform:
var convertData = function (d) {
var arr = [];
for(var prop in data)
{
var el = { "id": prop };
var otherprops = data[prop];
for(var otherprop in otherprops)
{
el[otherprop] = otherprops[otherprop];
}
arr.push(el);
}
return arr;
}
Tnis is what my sample data looks like after the conversion (slightly different values than yours):
[{"id":"-L8eoUd5mqJGnXDVSmb0","description":"With a great description","endDate":"12/31/2018","endTime":"03:00","imageUrl":"/favicon.ico","name":"Here's a Good Event","startDate":"12/01/2018","startTime":"12:00"},{"id":"-L8jO6Zhz976hvoLUiga","description":"Another item","endDate":"12/30/2018","endTime":"03:05","imageUrl":"/favicon2.ico","name":"Event #2","startDate":"12/11/2018","startTime":"12:03"}]
Link to JSFiddle: https://jsfiddle.net/2t1s2are/13/
Hope this helps!!

how to use a map in a JsonBuilder? i.e. how to create dynamic, not static Json in grails?

creating hard coded json is easy, e.g.
String createJson(Person person, list<Account> accounts) {
def builder = new JsonBuilder()
def json = builder {
person person
accounts accounts
}
return builder.toPrettyString()
}
The above works, and produces something like this:
{
"person":{
username": "user"
"firstName": "test"
}
"accounts":[
{
"balance": "200829.00",
"currency": "CRD",
"id": 1,
}
]
}
The problem is we have a REST api, which returns JSON. Curently, we have a lot of duplicate code, as we can't find a generic way to generate different parts of the JSON api response and combine them together and render the result, ether by merging json strings, or by dynamically buidling the json from a map, e.g the following doesnt work:
String createJson(Map map) {
def builder = new JsonBuilder()
def root = builder {
map.collect { key, value ->
"$key" value
}
}
return builder.toPrettyString()
}
then calling it like this:
Person person = someMethodToGetAPerson()
List<Account> accounts = someMethodToGetAccounts(person)
Map map = ["person", person, "accounts", accounts]
String json = createJson(map)
render(status: 200, contentType: 'application/json', text: json)
However, this fails, with a stack overflow in the bowels of grails.
In addition, we have defined several json marshallers which must be used, e.g.
JSON.registerObjectMarshaller(Account) {
return [balance: formatter.format(it.balance)....
}
Any ideas?
What I could understand is you want to convert a map into JSON string. For that you can use grails.converters.JSON class. For example
Person person = someMethodToGetAPerson()
List<Account> accounts = someMethodToGetAccounts(person)
Map map = [person: person, accounts: accounts]
String json = new JSON(map).toString()
The toString() method also takes an boolean value for preety printing. And it should honor your registered marshallers

JSON ignore fields outside data maps

I am getting some response :
var xxx_api = { "user" : {
"name":"satishpandey",
"sites":[
{
"name":"SEO Product",
"url":"http://www.xxx.com/"
} ]
}};
I want to exclude all the string those are outside json data.
var xxx_api and ; are needs to be excluded.
Is there anything in jackson to exclude these strings?
Assuming you are using this in a get/post (restful-like) method, maybe that has to do with the header of the webservice method you are using. I am using REST and I am able to specify the format I want to receive the json input like this
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response myMethod(#FormParam("post") String jsonInput){
// ...
// use jsonInput
mapper.readValue(jsonInput, ...);
// ...
}
Considering this, I guess the input written to the var jsonInput (in the header) would be
{ "user" : {
"name":"satishpandey",
"sites":[
{
"name":"SEO Product",
"url":"http://www.xxx.com/"
} ]
}};
I didn't find any solutions for it in jackson. Now I am using String.substring() method for getting the desired results.
StringBuilder stringBuilder = new StringBuilder(jsonString);
stringBuilder.replace(0, stringBuilder.indexOf("{"), "");
stringBuilder.replace(stringBuilder.lastIndexOf("}") + 1, stringBuilder.length(), "");
It is working perfectly for me.