MVC4: Include object name in Json - json

I have a question on a MVC4 (beta) issue I have been struggling with for some time now. The issue is that I want to create a json with the object name added for my webapi. The json has to be created this was as the receiving side needs this. My .NET/MVC knowledge is limited so please bear with me. I tried searching on the subject, but as MVC4 is still in beta it's difficult to find good info on this subject.
I have already imported the JSON.NET formatter in my solution, but this does not add the Object name
The json that is now created in MVC4:
[{"ID":36,"Name":"Test3","Description":"Description Test3"},{"ID": 37,"Name": "Test4","Description": "Description Test4"}]
And I would like the json to look like this:
{"Goal":[{"ID":36,"Name":"Test3","Description":"Description Test3"},{"ID": 37,"Name": "Test4","Description": "Description Test4"}]}
So I like the object name (Goal) to be included in the json.
The code in my api controller I am using for this is:
StoreDBContext db = new StoreDBContext();
//
// GET /api/goals
public IQueryable<Goals> Get()
{
return db.Goals;
}
I assume I need to loop through somewhere to add the object name, but I am not sure how... Hopefully someone can help me out with this!

Return something like this:
new { Goal = db.Goals().AsEnumerable().ToList() }
You can use an anonymous object to add properties and stuff that aren't in the object.
You can also write custom converters for JSON.NET if you want it to deserialize properly, but if you don't care about deserialization of the output, the above solution will work.

Related

How to deserialize JSON to object in Swift WITHOUT mapping

Is there a way to deserialize a JSON response to a custom object in Swift WITHOUT having to individually map each element.
Currently I am doing it manually with SwiftyJSON but it still requires me to map every field redundantly:
var myproperty1 = json["myproperty1"].stringValue
However coming from a C# background it is as simple as one line of code:
JsonConvert.DeserializeObject<CustomObject>(jsonString); //No mapping needed.
Source - http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Since I am writing many API endpoints I would like to avoid all the boilerplate mapping code that can be prone to errors. Keep in mind that my JSON responses will be multiple levels deep with arrays of arrays. So any function would need to be recursive.
Similiar question : Automatic JSON serialization and deserialization of objects in Swift
You could use EVReflection for that. You can use code like:
var user:User = User(json:jsonString)
or
var jsonString:String = user.toJsonString()
See the GitHub page for more detailed sample code
You should be able to use key value coding for this. You'd have to make your object a subclass of NSObject for KVC to work, and then you could loop through the elements of the JSON data and use setValue:forKey to assign a value for each key in the dictionary.
Note that this would be dangerous: If the target object did not contain a value for a specific key then your code would crash, so your program would crash on JSON data that contained invalid keys. Not a good thing.

Combine ember.js and asp.net webapi JSON formats

I am currently building a web app with ember.js and webapi 3.
Currently I am facing the problem that webapi sends a JSON result (of an array of DTOs) which doesn't get understood by ember because it is missing a root element.
I didn't got far with the solutions on the web, which mostly just pointed to a template project for VS.
Has someone a simple and understandable solution?
I'm going to assume you're talking about Ember-Data.
web-api sends back json in whatever format the object is, so if you're sending back a list/array it's going to return an array of objects. If you have control of the controller then just modify what it's returning.
return new { foos = new List<string>() };

Pass Json Object from Play! framework to HighCharts JS

http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application which sends data from the model to view via the Application controller.
I have managed to display the model(Tasks) as a high chart. The code is here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page.
http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer to lines 9-14 and lines 20-24.This unelegant style of doing things is not really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template.
And how to parse it into a Highcharts format. Is there some standard procedure to do this ? Or else I have to write my own method to do this ?
It'll great if someone can show me a code snippet. Also I would prefer a post not using Ajax. I would just want to know how to do this first.
I also found this stackoverflow post useful.how to parse json into highcharts. However, it didnt answer the part about converting from Play format to Highcharts format.
Thanks in advance
You don't need to pass a json object to your template, instead you might do an ajax call from your client side javascript (your template) and get json response that you could use futher in javascript code to build a chart. For example :
You have some path that is bind to your controller jsonIt() like so /chartsdata/json
then using jquery shorthand for ajax request:
var chart_data = $.get('/chartsdata/json', function(data) {
return data;
});
now you can use a chart_data that is an array of objects where each object represents a Task, in your further javascript code to build a chart.

List<Object> to JSON using annotations

OK, here goes, hopefully this makes sense! I have a small project based off of the appfuse web service only archetype. I have a business facade which has a DAO injected, through this DAO I request some data, simple example:
PersonManager.java
#GET
#Path("{people}")
List<Person> getPeople(#QueryParam("surname") String surname);
PersonManagerImpl.java (implements PersonManager)
public List<Person> getPeople(String surname) {
return personDao.getPeople(String surname);
}
I can make a request to invoke this method through a URL configured to point to "getPeople", however, as the DAO returns the list of people as an array list, I get the following error
Error serializing the response, please check the server logs, response class : ArrayList.
I know I can wrap this method and use Jackson Object Mapper to change the list to a string, but I didn't want another layer in my code, just to marshal JSON requests/responses.
I also don't want to change the interface to return a string, because the interface may be used later to return other data types, thus, I don't want to lock it in to only returning a string representing JSON.
My dilemma is that, I don't quite get how keeping the above interface and implementation, I can have Jackson convert the list of people to a json list of people, with annotations only!
Any help is greatly appreciated.
Please help!
Upgrading Jackson from 1.7.1 to 1.9.5 resolved this issue.

Is there a way to tell GSON to parse strings with type names at beginning?

from Jersey a classic JSON output of List looks like:
{"SubtaskType":{"id":"4","name":"mozaika","metric":"m2","code":"104"}}
But GSON will say it's not a JSON array and experimentally, it accepts:
{"id":"4","name":"mozaika","metric":"m2","code":"104"} for single SubtaskType.
I tested it with JSON validator and it seems that both forms are acceptable.
GSON's output of List looks like:
[{"name":"aa","metric":"m2","id":1,"code":200},{"name":"bb","metric":"m","id":2,"code":300}]
Is there a way to configure GSON to parse/generate the longer form (with type name)?
Edit:
This is the structure (added for change/discussion):
public class SubtaskType {
private int id;
private String name;
private String metric;
private int code;
//getters & setters
}
Note: This answer is based on the original version of the question.
from Jersey a classic JSON output of List looks like:
{"SubtaskType":{"id":"4","name":"mozaika","metric":"m2","code":"104"}}
Really? That's not a JSON array, i.e., list. It's an object with one element named "SubtaskType", for which the element's value is an object with four elements. There is no list.
Is that just what a list with a single component comes out like? Does a list with two components come out like
{"SubtaskType":[{"id":"4","name":"mozaika","metric":"m2","code":"104"},{"name":"bb","metric":"m","id":2,"code":300}}
If this is the case, and you must receive such poorly-generated* JSON, and you must use Gson, then you'll have to implement custom deserialization processing to handle the situation where it's sometimes a list and it's sometimes an object. This is an all-too-often occurring problem. Gson unfortunately does not yet have a simple configuration available to handle this often-occurring problem. I posted an example of such custom deserialization processing in response to the question at Parsing JSON with GSON, object sometimes contains list sometimes contains object
* Just because it's valid JSON, doesn't mean it's not crap. An API should generate consistently-structured JSON. Anything less is crap.
GSON's output of List looks like:
[{"name":"aa","metric":"m2","id":1,"code":200},{"name":"bb","metric":"m","id":2,"code":300}]
Good. That's what a list in JSON is supposed to look like.
Is there a way to configure GSON to parse/generate the longer form (with type name)?
Yes. The specific solution depends on what your Java data structure currently looks like, and whether you're able to change the structure to match the desired JSON. If you cannot change the Java data structure accordingly, then you must custom process serialization/deserialization. Post the Java data structure you'd like to use, and indicate whether it can be changed.
Also, post an exact example of the "longer form" JSON you want to generate that represents a list with at least two components. You have not done this, yet. So, it leaves me guessing about what you really want to do.
It does seem pretty clear that you want polymorphic type handling in whatever the ultimate solution is. This will require custom deserialization processing, if using Gson.
Regarding any question on polymorphic deserialization, please note that the issue was discussed a few times on StackOverflow.com already. I posted a link to four different such questions and answers (some with code examples) at Can I instantiate a superclass and have a particular subclass be instantiated based on the parameters supplied.
For polymorphic serialization, not only will it likely be necessary to implement custom serialization to generate the desired type element, but convincing Gson to serialize all of the fields from polymorphic types also requires custom processing. See Serializing List of Interfaces GSON for more information.