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
Related
I have form data coming from the front end that gets passed through graphql to my postgreql database. In an effort to avoid passing a long list of strings through graphql i wanted to use json. After exhausting my google and DOC options I am humbly asking for help understanding how this is done. In the end if i can just get a valid json object into my AddForm resolver id be happy. Thanks in advance to your time.
The Mutation looks like this
mutation AddForm ($formHeader: String!, $formBody: String!, $formComments: String!) {
addForm(formHeader: $formHeader, formBody: $formBody, formComments: $formComments) {
id
formHeader
formBody
formComments
}
}
The variables look like this (simplified for example purposes)
$formHeader
{
"name": "graylagx",
"date": "today",
"equipment": "water",
}
$formBody
{
"InternalCheckList": {
"Check1": "yes",
"Check2": "N/A",
},
"ExternalCheckList": {
"Check1": "yes",
"Check2": "yes",
}
}
$formComments
"This is a very long comment string"
The second parameter in the graphql resolver for addForm mutation will have all the input variables as a JSON object with keys formHeader, formBody, and formComments and values as defined by the inputs in your schema
I'm building a Restful API using Spring Boot and I'm running into a problem.I have an entity called Event, it has the following attributes:
Long id, String title, Calendar date, List< User > owners (OneToMany), Double price.The Entity, in turn, has the these attributes: Long id, String name, Calendar birthDate, List< Car > cars.Entity Car, in turn, has Long id and String model as attributes.
The problem is, when I access the HTTP Method GET in my Event Controller, I get this JSON:
{
"id":1,
"title":"Example event",
"date":"2017-01-01",
"owners":[
{
"id":1,
"name":"Chuck Norris",
"birthDate":"1000-05-12",
"cars":[
{
"id":1,
"model":"Shelby GT"
}
]
},
{
"id":2,
"name":"Bruce Lee",
"birthDate":"1980-05-12",
"cars":[
{
"id":2,
"model":"Ford Maverick"
}
]
}
],
"price":5
}
Instead of serializing whole owners objects, I want just their ID, like this:
{
"id":1,
"title":"Example event",
"date":"2017-01-01",
"owners":[
{
"id":1
},
{
"id":2
}
],
"price":5
}
How can I achieve this? And, is this correct to use? I think that serializing whole inner objects is a waste of resource because I don't need all their attributes at the moment, and it also causes loop with bi-directional relationships
For this use-case I developed a small jackson module for dynamic filtering:
https://github.com/Antibrumm/jackson-antpathfilter
The second possibility would be to build DTOs for your endpoints.
Add #JsonIgnore Annotation to fields that you don't want to be serialized
It sounds like you want to return a custom view of the Event, but you may actually be better off with the full object, depending on what the user of your API needs to do with the Event. One option, especially since you commented that other calls need the full User object to be serialized, is to configure the ObjectMapper used in this method with a custom serializer for User.
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
)
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
]
Is there a standardized way to store classes in JSON, and then converting them back into classes again from a string? For example, I might have an array of objects of type Questions. I'd like to serialize this to JSON and send it to (for example) a JavaScript page, which would convert the JSON string back into objects. But it should then be able to convert the Questions into objects of type Question, using the constructor I already have:
function Question(id, title, description){
}
Is there a standardized way to do this? I have a few ideas on how to do it, but reinventing the wheel and so on.
Edit:
To clarify what I mean by classes: Several languages can use classes (JAVA, PHP, C#) and they will often communicate with JavaScript through JSON. On the server side, data is stored in instances of classes, but when you serialize them, this is lost. Once deserialized, you end up with an object structure that do not indicate what type of objects you have. JavaScript supports prototypal OOP, and you can create objects from constructors which will become typeof that constructor, for example Question above. The idea I had would be to have classes implement a JSONType interface, with two functions:
public interface JSONType{
public String jsonEncode();//Returns serialized JSON string
public static JSONType jsonDecode(String json);
}
For example, the Question class would implement JSONType, so when I serialize my array, it would call jsonEncode for each element in that array (it detects that it implements JSONType). The result would be something like this:
[{typeof:"Question", id:0, title:"Some Question", description:"blah blah blah"},
{typeof:"Question", id:0, title:"Some Question", description:"blah blah blah"},
{typeof:"Question", id:0, title:"Some Question", description:"blah blah blah"}]
The javascript code would then see the typeof attribute, and would look for a Question function, and would then call a static function on the Question object, similar to the interface above (yes, I realize there is a XSS security hole here). The jsonDecode object would return an object of type Question, and would recursively decode the JSON values (eg, there could be a comment value which is an array of Comments).
You'll have to create your own serializer which detects Question (and other classes) and serializes them as constructor calls instead of JSON object notation. Note that you'll need a way to map an object to a constructor call. (Which properties come from which parameters?)
Everyone else: By classes he means functions used as constructors; I assume that he's trying to preserve the prototype.
Have you looked at JSON.NET? It can serialize/de-serialize .NET objects to JS and vice-versa. It is a mature project and I highly recommend it.
Also, if you could change the definition of your 'Question' function to take one object with properties instead of taking separate arguments, you can do something like this:
Working Demo
function Question(args)
{
this.id = args.id;
this.text = args.text;
}
Question.prototype.alertText = function() { alert(this.text); };
$(document).ready(
function()
{
var objectList =
{
'list' : [
{ 'id' : 1, 'text' : 'text one' }
,{ 'id' : 2, 'text' : 'text two' }
,{ 'id' : 3, 'text' : 'text three'}
],
'type' : 'Question'
};
var functionName = objectList['type'];
var constructor = window[functionName];
if(typeof constructor !== 'function')
{
alert('Could not find a function named ' + functionName);
return;
}
var list = objectList['list'];
$.each(list,
function()
{
var question = new constructor(this);
question.alertText();
}
);
}
);
On a side note, please prefix your .NET Interfaces with 'I' e.g. it should be IJsonType and not JsonType.
typeof is a keyword so specify the property name in quotes if you want to use it.
It's highly dangerous, but eval can process any text and execute it.
http://www.w3schools.com/jsref/jsref_eval.asp
But DON'T use it. May do something like pass over the params you want to pass into the constructor as a JSON object and call the constructor with it...
function Question({"id" : "val", "title", "mytitle", "description" : "my desc"}){
...
}
This might be useful.
http://nanodeath.github.com/HydrateJS/
https://github.com/nanodeath/HydrateJS
Use hydrate.stringify to serialize the object and hydrate.parse to deserialize.
Assuming you are using a Javascript client and a REST api backend and you are looking to define the rules for encoding a Method as JSON, you should probably consider using graphQL.
You could also look at my draft Specificaton for JSON-ND - that may give you simple representation: eg
Where the server publishes this specification:
{
"Question:POST(id:integer, title:string, description:string):string" :
"https://my.question.com:999/question"
}
Or perhaps a little less "C" style
{ "QuestionParam:Interface"[
"id:integer",
"title:string",
"description:string"
],
"Question:POST(QuestionParam[0,]):string" :
"https://my.question.com:999/question"
}
This means you can POST the following to https://my.question.com:999/question
{
"questions:Question": [
{id:0, title:"Some Question 1", description:"blah blah blah"},
{id:1, title:"Some Question 2", description:"blah blah blah"},
{id:2, title:"Some Question 3", description:"blah blah blah"}
]
}
And the server would respond with something like:
[
"answer 1",
"answer 2",
"answer 3",
]
You might even define a better return type say "Answer"
{
"Answer:Interface"[
"id:integer",
"answer:string"
],
"Question:POST(id:integer, title:string, description:string):Answer" :
"https://my.question.com:999/question:URI"
}
And the server would return:
{ "answers:Answer" :[
{"id":0, "answer":"Answer 1"},
{"id":1, "answer":"Answer 2"},
{"id":2, "answer":"Answer 3"}
]
}
on the client side, implement a JSON-ND interpreter similar to the example:
, include a Fetch call and you could use something like:
var questions = {
"questions:Question": [
{id:0, title:"Some Question 1", description:"blah blah blah"},
{id:1, title:"Some Question 2", description:"blah blah blah"},
{id:2, title:"Some Question 3", description:"blah blah blah"}
]
}
var answers = JSON_ND_Stringify(questions) ; //of course use an async call here