I have been trying to fill my Google chart dynamicly, like this example:
https://developers.google.com/chart/interactive/docs/php_example
I'm using this dependency for the DataTable class and others:
<dependency>
<groupId>com.google.visualization</groupId>
<artifactId>visualization-datasource</artifactId>
<version>1.1.1</version>
</dependency>
This is the API for the DataTable class:
https://developers.google.com/chart/interactive/docs/dev/dsl_javadocs/com/google/visualization/datasource/datatable/DataTable
I'm using a Java HttpServlet that contains this code (example) to populate the DataTable:
DataTable dataTable = new DataTable();
dataTable.addColumn(new ColumnDescription("uur", ValueType.TEXT, "Uur"));
dataTable.addColumn(new ColumnDescription("aantal", ValueType.NUMBER, "Aantal spellen"));
try {
dataTable.addRowFromValues("1", 5, true);
dataTable.addRowFromValues("2", 9, true);
dataTable.addRowFromValues("3", 17, true);
} catch (TypeMismatchException ex) {
Logger.getLogger(VerkrijgChartDataServlet.class.getName()).log(Level.SEVERE, null, ex);
}
I also included this to make it return JSON:
response.setContentType("application/json");
Then with Gson I convert it to a JSON string:
new Gson().toJson(dataTable);
This returns a string of the format:
{
"columnIndexById" : {"aantal":1, "uur":0},
"columns" : [
{"id":"uur","label":"Uur","pattern":"","type":"TEXT"},
{"id":"aantal","label":"Aantal spellen","pattern":"","type":"NUMBER"}
],
"rows" : [
{"cells":[{"value":{"value":"1"}},{"value":{"value":5.0}}]},
{"cells":[{"value":{"value":"2"}},{"value":{"value":9.0}}]},
{"cells":[{"value":{"value":"3"}},{"value":{"value":17.0}}]},
],
"warnings" : []
}
But then Google Chart says: 'Table has no colums.'
Google's example JSON looks like this:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
Does anyone has an idea of what I'm doing wrong? Do I need to do something else?
Thanx in advance.
A bit late but better late then never. I think I know the answer to your question.
You actually know the answer. In your question, you give a Google Chart JSON example. The JSON string needs to start with
{"cols":...}
while your JSON string, rendered by gson, starts with
{"ColumnIndexById":{...},
"columns":...
}
If you pass a json string to a google DataTable visualisation, then its structure needs to look exactly like the Google Example. So instead of "columns", it needs to be "cols".
You can to use the JsonRenderer of API
JsonRenderer.renderJsonResponse(
DataSourceParameters.getDefaultDataSourceParameters(), null, data
)
Related
My Backend Rails API consumes POST requests in the form of
{
"name": "Mark White",
"email" : "mark#xyz.com"
}
Have tried this in Postman and this creates a record successfully.
In my ember frontend, Im using the following code to create a new record, from a form input:
app/routes/addUser.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
addUser(){
let formData = {
"name": this.controller.get('name'),
"email": this.controller.get('email')
};
let newUser = this.store.createRecord('user',formData);
newUser.save();
}
}
});
which generates the request as
{
"user": {
"name": "Mark White",
"email" : "mark#xyz.com"
}
}
which my backend is not prepared to handle and throws an error.
Any way I can quickly conform to the json format that works for me in Postman.
When the question is along the lines with the "How can I change my payload to server for it to be in a certain format?" then you should have a look at customizing a serializer.
But it looks like for solving your problem you might wanna take the standard JSON Serializer; in your app/serializers/application.js just type the following:
import JSONSerializer from '#ember-data/serializer/json';
export default class ApplicationSerializer extends JSONSerializer {
// ...
}
Note that it's for the Ember.js v4, according to your example you're using a bit older version so just adjust the syntax accordingly.
I have a problem recently.
springboot receive request, but strange!
how to use entity mapping this data below
This strange data:
a=
{
b=
{
b1=null,
b2=1,
b3=null,
b4=null,
b5=null
},
c={
c1=null,
c2=1,
c3=nfsaf
},
ds=
[
{
d1=dsdsadad,
d2=null,
d3=null
},
{...}
]
}
I try use jackson or gson to convert it,but error.
If there is no good way,i finally use regular expression to catch!
that`s all,Ignore these,Ignore these,Ignore these,Ignore these
very grateful to you for your help!
Consider the following json:
{
"title": "SOME TITEL",
"status": 500,
"detail": "Some detail",
"errors": [
{
"Parameter": "SOME VALUE",
"Code": "SOME CODE",
"Message": "SOME MESSAGE",
"Details": "SOME EXTRA DETAILS"
}
]
}
It is generated by an API response that construct a problem details like this:
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError;
Detail = "DETAIL";
Title = "TITLE";
};
var customClass = new CustomCalss
{
Code = "INTERNAL_SERVER_ERROR",
Message = "Some message",
Details = "Extra details"
};
problemDetails.Extensions.Add(new KeyValuePair<string, object>("errors", new [] { customClass }));
When trying to deserialize the json to a problem details using System.Text.JsonSerialiser i found the following issues:
Status, Code and Title are not deserialised to the problem details properties, they are null
Extension data is not deserialized.
I'm testing this behavior like this:
var json = #"{
""title"": ""SOME TITLE"",
""status"": 500,
""detail"": ""Some detail"",
""errors"": [
{
""Parameter"": null,
""Code"": ""SOME CODE"",
""Message"": ""SOME MESSAGE"",
""Details"": ""SOME EXTRA DETAILS""
}
]
}";
var result = JsonSerializer.Deserialize<ProblemDetails>(json);
Assert.NotNull(result.Detail);
Assert.NotNull(result.Title);
var customClass = Assert.IsType<CustomCalss[]>(result.Extensions["errors"]);
var error = customClass.First();
Assert.Equal("INTERNAL_SERVER_ERROR", error.Code);
Any insights?
C# is a case sensitive language, something wrong with your JSON string, the key must exactly same with the property of the target class. I changed the "title" to "Title" and then got the correct value, attached here for your reference:
Updated on 11/20:
Did not noticed that it is a MVC internal class, we can simple reproduce this issue in local box now, but checked the source codes and known issues online, no existing related issue there. So I reported a new bug for this issue, attached here for your reference
https://github.com/aspnet/AspNetCore/issues/17250
Updated on 11/22:
This has been confirmed as a bug in ASP.NET Core 3.0, and fixed in 3.1 version, please upgrade to 3.1-preview2. Alternatively you could specify a custom JsonConverter based on the implementation we have in 3.1 as part of the JsonSerializerOptions that you pass when deserializing - https://github.com/aspnet/AspNetCore/blob/release/3.1/src/Mvc/Mvc.Core/src/Infrastructure/ValidationProblemDetailsJsonConverter.cs
I have created a JSON object using VB.NET
{
"MasDatos": {
"Cosas": "Yo que se",
"MasCosas": "Ni idea",
"OtroArray": [
"Cosa 1",
"Cosa 2",
"Cosa 3"
]
},
"nombre": "Person Name",
"apellidos": "Second Name",
"edad": 19,
"Gustos": [
"Gusto 1",
"Gusto 2"
]
}
I Send this code to my WCF Service on "POST" Method. I can read all variables, for example.
If i want to read "edad" i can do something like this in my wcf service method...
public String readParameter(String edad){
return edad;
}
above code works. But I CANT read "MasDatos" values. That is a Dictionary. But im not able to retrieve it.
If you see, "Gustos" is an array. I can read it doing this
public string readValue(array Gustos){
//Logical stuff
}
i've tried doing this to read "MasDatos"
public string readDicto(List<String,Object> myNewDictionary){
return somestring;
}
but myNewDictionary is null everytime...
Please forgive my horrible english. I hope someone can help me =)
Thanks in advance!!
Well, answer is quite simple.
Use classes with [datacontract] and [datamember] tags to map complex json objects
I am using Grails 2.1 to render JSON as part of a RestFul API I created. The Domain class, based on a SqlServer table, looks like this:
String firstName
String lastName
String officialAddress1
String officalAddress2
String preferredAddress1
String preferredAddress2
(etc.). . .
Which returns JSON similar to this:
{
"firstName": "Joe",
"lastName": "Hill",
"officialAddress1": "1100 Wob Hill",
"officialAddress2": "Apt. # 3",
"preferredAddress1": "1100 Wobbly Lane.",
"preferredAddress2": "Apartment 3."
}
It is working fine but the client wants me to nest the results in this fashion:
{
"firstName": "Joe",
"lastName": "Hill",
preferredAddress {
"preferredAddress1": "1100 Wobbly Lane.",
"preferredAddress1": "Apartment 3."
},
officialAddress {
"officialAddress1": "1100 Wob Hill",
"officialAddress2": "Apt. # 3"
}
}
My question is since the domain class, and the database, are not structure in a way to return this type of nested result how can I easily change this in my returned JSON? Do I have to abandon my way of just regurgitating the JSON based on the database/domain object and do a custom converter of some kind?
i'm new to this stackoverflow thing and i hope i will not mess it but i think i know what you need. in your bootstrap.groovy file you find "def init = { servletContext -> " line
put in there something like this:
JSON.registerObjectMarshaller(YourDomainName) {
def returnArray = [:]
returnArray['firstName'] = it.firstName
returnArray['lastName'] = it.lastName
returnArray['preferredAddress'] = [it.preferredAddress1 ,it.preferredAddress2]
returnArray['officialAddress'] = [it.officialAddress1 ,it.officialAddress2]
return returnArray
}
now when you use the render with JSON as you did grails will look in bootstrap and
render the domain as you asked.
hope this helps
The posted answer was correct. I just wanted to add the slight change I made to get the exact results I needed:
Thanks! That did it. I originally that it would not work exactly how I needed it but I was wrong. I changed the syntax slightly to get the results I needed.
returnArray['preferredAddress'] = [address1: it.preferredAddress1?.trim(),
address2: it.preferredAddress2?.trim(),
address3: it.preferredAddress3?.trim(),
city: it.preferredCity,
state: it.preferredState,
postCode: it.preferredPostCode,
country: it.preferredCountry
]