Return inline JSON from endpoint - json

Mostly this is about just sending hard coded JSON from Web API method back to a caller app ( happens to be React). My current action looks something like the following:
[Route("members/{memberId}")]
public async Task<IActionResult> Members(string memberId)
{
// {
// "SecA4": ["Asian"]
// }
// ?? string json = "{ \"SecA4\": [\"Asian\"] }"; //??
return OK() // need to place JSON in the OK() method. but how should it be done?
}
So currently I am able to load from a file into a survey engine a file that looks like that. Thus I load from a .json file.
{
"SecA4": ["Asian"]
}

Rather then a hard-coded string I would use an object rather, which would be done something like the following
object someObject = new
{
SecA4 = "Asian"
};
You can create this pretty much the same way as you would do with Json.
Now we are just returning the newly created object and converting it into Json.
return Json(someObject, new JsonSerializerSettings() { Formatting = Formatting.None });
Where in the JsonSerializerSettings you can tell Newtonsoft.Json to no use any formatting e.g. new lines, spaces and so on.

Related

Parse Json Response through Dictionary object

I have Json response through Facebook API like this:
Now I want to parse this data so I can use within my game. For this purpose, I have written code up to this:
public void OnChallengesButtonClick ()
{
SoundManager.Instance.PlayButtonClickSound ();
FB.API ("/me/friends", HttpMethod.GET, RetrieveFacebookFriends);
}
public void RetrieveFacebookFriends (IGraphResult result)
{
if (!string.IsNullOrEmpty (result.Error)) {
Debug.Log ("ERROR: " + result.Error);
return;
}
IDictionary<string,object> friendsDict = result.ResultDictionary;
Debug.Log ("raw: " + result.RawResult);
}
So how to extract name and ID data from available Json response through Dictionary object?
Basically you should create a class to serialize/deserialize an object:
class FBResponse
FBDataResponse data;
class FBDataResponse
string name;
string id;
Take a look to my response here for more details (after "Final EDIT" part):
Converting arrays of arrays to json
It should be easy to create those two class and use them to deserialize the FB response. Just remember that your variables will need to match the same name with the json response from Facebook (for example you cannot call data data1).
After you have the object it should be easy to do what you want with it... and with the object you should be able to get the json again.
PS. Unity default json serializer does not support Dictionary that's why you need to serialize two object. If you don't want that you should try to use a different library.
I think this is all I need: JSON with Unity
friends = (List<object>)(((Dictionary<string, object>)friendsH) ["data"]);
if(friends.Count > 0) {
var friendDict = ((Dictionary<string,object>)(friends[0]));
var friend = new Dictionary<string, string>();
friend["id"] = (string)friendDict["id"];
friend["first_name"] = (string)friendDict["first_name"];
}
Before I can't able to find this post from Facebook.

Grails: Easy and efficient way to parse JSON from a Request

Please pardon me if this is a repeat question. I have been through some of the questions/answers with a similar requirement but somehow got a bit overwhelmed and confused at the same time. My requirement is:
I get a JSON string/object as a request parameter. ( eg: params.timesheetJSON )
I then have to parse/iterate through it.
Here is the JSON that my grails controller will be receiving:
{
"loginName":"user1",
"timesheetList":
[
{
"periodBegin":"2014/10/12",
"periodEnd":"2014/10/18",
"timesheetRows":[
{
"task":"Cleaning",
"description":"cleaning description",
"paycode":"payCode1"
},
{
"task":"painting",
"activityDescription":"painting description",
"paycode":"payCode2"
}
]
}
],
"overallStatus":"SUCCESS"
}
Questions:
How can I retrieve the whole JSON string from the request? Does request.JSON be fine here? If so, will request.JSON.timesheetJSON yield me the actual JSON that I want as a JSONObject?
What is the best way to parse through the JSON object that I got from the request? Is it grails.converters.JSON? Or is there any other easy way of parsing through? Like some API which will return the JSON as a collection of objects by automatically taking care of parsing. Or is programatically parsing through the JSON object the only way?
Like I said, please pardon me if the question is sounding vague. Any good references JSON parsing with grails might also be helpful here.
Edit: There's a change in the way I get the JSON string now. I get the JSON string as a request paramter.
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON) // No problem here. Returns a JSONObject. I checked the class type.
def jsonArray = jsonArray.timesheetList // No problem here. Returns a JSONArray. I checked the class type.
println "*** Size of jsonArray1: " + jsonArray1.size() // Returns size 1. It seemed fine as the above JSON string had only one timesheet in timesheetList
def object1 = jsonArray[1] // This throws the JSONException, JSONArray[1] not found. I tried jsonArray.getJSONObject(1) and that throws the same exception.
Basically, I am looking to seamlessly iterate through the JSON string now.
I have wrote some code that explains how this can be done, that you can see below, but to be clear, first the answers to your questions:
Your JSON String as you wrote above will be the contents of your POST payload to the rest controller. Grails will use its data binding mechanism to bind the incomming data to a Command object that your should prepare. It has to have fields corresponding to the parameters in your JSON String (see below). After you bind your command object to your actual domain object, you can get all the data you want, by simply operating on fields and lists
The way to parse thru the JSON object is shown in my example below. The incomming request is esentially a nested map, with can be simply accessed with a dot
Now some code that illustrates how to do it.
In your controller create a method that accepts "YourCommand" object as input parameter:
def yourRestServiceMethod (YourCommand comm){
YourClass yourClass = new YourClass()
comm.bindTo(yourClass)
// do something with yourClass
// println yourClass.timeSheetList
}
The command looks like this:
class YourCommand {
String loginName
List<Map> timesheetList = []
String overallStatus
void bindTo(YourClass yourClass){
yourClass.loginName=loginName
yourClass.overallStatus=overallStatus
timesheetList.each { sheet ->
TimeSheet timeSheet = new TimeSheet()
timeSheet.periodBegin = sheet.periodBegin
timeSheet.periodEnd = sheet.periodEnd
sheet.timesheetRows.each { row ->
TimeSheetRow timeSheetRow = new TimeSheetRow()
timeSheetRow.task = row.task
timeSheetRow.description = row.description
timeSheetRow.paycode = row.paycode
timeSheet.timesheetRows.add(timeSheetRow)
}
yourClass.timeSheetList.add(timeSheet)
}
}
}
Its "bindTo" method is the key piece of logic that understands how to get parameters from the incomming request and map it to a regular object. That object is of type "YourClass" and it looks like this:
class YourClass {
String loginName
Collection<TimeSheet> timeSheetList = []
String overallStatus
}
all other classes that are part of that class:
class TimeSheet {
String periodBegin
String periodEnd
Collection<TimeSheetRow> timesheetRows = []
}
and the last one:
class TimeSheetRow {
String task
String description
String paycode
}
Hope this example is clear enough for you and answers your question
Edit: Extending the answer according to the new requirements
Looking at your new code, I see that you probably did some typos when writting that post
def jsonArray = jsonArray.timesheetList
should be:
def jsonArray = jsonObject.timesheetList
but you obviously have it properly in your code since otherwise it would not work, then the same with that line with "println":
jsonArray1.size()
shuold be:
jsonArray.size()
and the essential fix:
def object1 = jsonArray[1]
shuold be
def object1 = jsonArray[0]
your array is of size==1, the indexing starts with 0. // Can it be that easy? ;)
Then "object1" is again a JSONObject, so you can access the fields with a "." or as a map, for example like this:
object1.get('periodEnd')
I see your example contains errors, which lead you to implement more complex JSON parsing solutions.
I rewrite your sample to the working version. (At least now for Grails 3.x)
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON)
println jsonObject.timesheetList // output timesheetList structure
println jsonObject.timesheetList[0].timesheetRows[1] // output second element of timesheetRows array: [paycode:payCode2, task:painting, activityDescription:painting description]

RestSharp: get JSON string after deserialization?

using RestSharp is there a way to get the raw json string after it has been deserialized into an object? I need that for debugging purposes.
I'd like to see both the deserialized object and the originally received json string of that object. It's part of a much bigger json string, an item in an array and I only need that specific item json code that's got deserialized into the object.
To help you out this should work, this is a direct example of some of my work, so your's might be a bit different.
private void restClient()
{
string url = "http://apiurl.co.uk/json";
var restClient = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddParameter("apikey", "xxxxxxxxxx");
restClient.ExecuteAsync<Entry>(request, response =>
{
lstboxtop.Items.Add(response.Content);
});
}
The line lstboxtop is a listbox and using the response.content will literally print the whole api onto your app, if you call it first that would be what you are looking for

WebClient.DownLoadString is adding \" infront of my JSON data elements.How to parse it as normal JSON without \"?

I am trying to access a REST Service in my MVC application.I am calling getJSON method to get the data from a controller which internally calls the REST service which returns data in json format.But I am getting the a lot of "\ in my output of DownLoadString method and my return Json is not returning proper JSON data and hence my client side script is not able to access the JSON properties.
My Script in my view is
$.getJSON("#Url.Action("GetManufacturers", "Home")",function(data){
console.debug("Status is : "+data.Status)
});
My Action method looks like this
public ActionResult GetManufacturers()
{
string restURL ="http://mytestserver/myapi/Manufacturers";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
//data variable gets "\" everywhere
return Json(data,JsonRequestBehavior.AllowGet);
}
}
I used visual studio breakpoints in my action method and i am seeing a lot of \"
And i checked what is coming out to my getJSON callback and the JSON tab is empty.
But my response tab has content like this
I belive if there is no \", i would be able to parse it nicely.
I used fiddler to see whether i am getting correct (JSON format) data from my REST service and it seems fine.
Can anyone help me to tackle this ? I would like to return proper JSON from my action method. Sometime i may want to read the json properties in the C# code itself. I saw some example of doing it with DataContractJsonSerializer. But that needs a concrete type to be converted to. I don't want to do that. because other clients would also access my RESTService and how will expect them to write a fake entity for this ?
You need to return the data as is:
public ActionResult GetManufacturers()
{
string restURL ="http://mytestserver/myapi/Manufacturers";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
return Content(data, "application/json");
}
}

Is there a way to add an additional field to Grails JSON response?

I want every JSON response to post-request to contain a field success. What's the best way to add this field there?
I use code like this to generate JSON responses:
try {
def entity = myService.saveEntity(arg1,arg2)
render entity as JSON //I want to add artificial field 'success = "yes"' here
} catch (ValidationException e) {
render parseErrors(e.errors) as JSON //field 'success = "no"' here
}
I just struggled with this exact issue this week. I wanted to send back a domain class as JSON but at the same time add an 'errorMessage' property that would potentially contain additional information.
Turns out that when using as JSON in grails it sends back a converter object, but its possible to turn that converter instance into a jsonObject using JSON.parse() which we can easily add new values to.
def jsonObject = JSON.parse((entity AS JSON).toString())
jsonObject.put("success", "yes")
render jsonObject as JSON
I think there are a couple of different approaches but this ended up being the easiest for me since I already have custom converters for most of my domain classes and I didn't want to add any other transient properties to my domain object.
Could you return a map containing the success field, and the object wrapped inside a separate variable:
try {
def entity = myService.saveEntity(arg1,arg2)
render [ success:'yes', val:entity ] as JSON
} catch (ValidationException e) {
render [ success:'no', val:parseErrors(e.errors) ] as JSON
}
Not tested it mind...
You can register your own JSON marshaller (at BootStrap.groovy, for example), like:
JSON.registerObjectMarshaller(MyEntity) { MyEntity it ->
return [
someField : it.someField, // you should specify fields for output, or put all '.properties'
success : true // as I understand you always have 'true' for real entity
]
}
where MyEntity is your class you want to use