This may be a stupid question but I want to ask because it may be an indication of a mistake I may be making.
I just created my first Web API project and started hosting it as a website. Initially, I was getting XML responses, so I added the following line in the Register method:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
I now get JSON results but my JSON results are not nicely formatted. They all come back as a regular string.
I get this:
{ "id": 123, "firstName": "John", "lastName": "Smith",
"gender": "male"}
I've seen a lot of examples where the result looks like this:
{
"id": 123,
"firstName": "John",
"lastName": "Smith",
"gender": "male"
}
Am I doing something wrong?
-- Edit ---
Thank you all for your response.
I wonder if the way I'm returning the data is causing this formatting issue. I'm just returning my POCO class and lettting the Web API handle any serialization. Is this the right way to return my data?
public IHttpActionResult GetSpecifiedPerson(int id)
{
Person user = new Person();
user.PersonId = 1234567;
user.FirstName = "Jane";
user.LastName = "Doe";
return Ok(user);
}
There is nothing wrong with your JSON. When you parse that you won't face any problems.
your JSON result is completely fine. nothing wrong.
most examples are formatted nicely for readability. nothing else
Related
I'm trying to use Katalon Studio for some webservice automation. I have been following this guide on how to parse returned Json body using jsonslurper.
https://docs.katalon.com/katalon-studio/tutorials/parse_json_responses.html
Everything is working fine as described in the guide. I wanted to see if I can use junit asserts, specifically the assertEquals() for better error text.
Given we have this
import groovy.json.JsonSlurper
String jsonString = {"menu": {
"id": "file",
"tools": {
"actions": [
{"id": "new", "title": "New File"},
{"id": "open", "title": "Open File"},
{"id": "close", "title": "Close File"}
],
"errors": []
}}}
JsonSlurper slurper = new JsonSlurper()
Map parsedJson = slurper.parseText(jsonString)
def array1 = parsedJson.menu.tools.actions
String onlickValue1 = ""
for(def member : array1) {
assertEquals("Open File", member.title)
break
}
What I'm having trouble with, is that my assert will thrown an error when comparing the very first title element it encounters (which is "New File").
What I intend is to loop through all the elements in the array and assert my expected value against all of them. If my expected value doesn't exist, then I'd fail.
I feel like I'm missing something, because we've done something similar in the past with java, but I just can't see it here.
So I figured out the problem was my inexperience/ignorance. When looking for solutions online I failed to understand with absolute certainty what the code I'm trying to implement is doing. I was using a for.each loop to assert elements in the array against my expected value. Which of course was failing, correctly, for every element that didn't match my expected value. So I made it work by adding an if statement as below:
String expectedValue = ''
for(def member : array1) {
if (member.title=="Open File")
{
expectedValue = member.title
}
break
}
assertEquals("Open File", member.title)
Also a simpler way I discovered is to use assertJ in the following way
assertThat(member).contains("Open File")
I understand there are better solutions to achieve what I'm trying to do. But for purposes of this question I considered it solved.
I have a JSON array, something like:
[{
"name": "John Smith",
"occupationId": 3
},
{
"name": "Steven Davis",
"occupationId": 2
}
]
The occupation response looks something like:
[{
"id": 2,
"name": "Teacher"
},
{
"id": 3,
"name": "Teaching Assistant"
}
]
Is there a way to allow RestKit to request the correct data for the occupations, given only their id? I know this can be done if the data is persisted using CoreData, via the addConnectionForRelationship:connectedBy: method, but I would rather that the data is transient, given that the server is local and there really is no need to persist the data. I'm also aware that RKObjectMapping does not support the identifiactionAttributes property, meaning I cannot (to my knowledge) designate a way to allow the class to declare a unique, identifying property.
Any help would be appreciated. I am using a mix of Objective-C and Swift, and as such, I do not mind answers in either language.
I am using MVC 4 WebApi to post several entities to Azure Table Storage. I believe that it's using formatting and not model binding because these are complex types (classes I've written) and they're being sent to the API in the body, not the URI.
This is working well for all of the entities except for one (a class called Comment), which points to the other entities (it has properties of the other entities). The JSON that I pass into the API in the body has 2 properties that contain other entities.
For Azure Table Storage, each entity has a RowKey attribute. I've noticed that once my controller builds the entity from the JSON in the request body (using the MVC4 formatting), it has the wrong value for the RowKey - it actually has the value for one of the entities referenced in the 2 properties that I mentioned. This other entity's RowKey attribute is also included in the JSON - so the JSON has 3 RowKeys, but they're all properly located in the JSON to be part of the correct entity. The Formatter just seems to be reading it wrong.
I can't save this Comment. I don't think the key problem is the reason, because the Table Storage service shouldn't care (there's no validation), but I believe that this is just part of a problem that makes the entity unsaveable by the Azure Table Storage service. Has anyone had similar problems with MVC formatting like this?
Thanks!
Edit
I forgot to mention - for testing, if I instantiate a new Comment entity inside the same controller method where the formatter is breaking, it saves just fine. So I'm fairly certain that the problem is occurring in the WebApi's parsing of the entity being passed to the controller's Post method.
Adding JSON and Model:
{
"PartitionKey": "US",
"RowKey": "com-dd1920ed-2e87-4f51-a6d1-32fa692aadae",
"AboutKey": "US|per-fb1de571-7142-47c8-bdb3-0eddd59f6ccd",
"FromPersonKey": "US|per-4c3261d8-3b1a-4bd4-8850-4d769cfbd7ef",
"CommentText": "Testing Create.",
"FromPerson": {
"PartitionKey": "US",
"RowKey": "per-4c3261d8-3b1a-4bd4-8850-4d769cfbd7ef",
"FirstName": "John",
"LastName": "Smith",
"NickName": null,
"FullName": "John Smith",
"Description": null,
"ImageLocation": null,
"Region": "US"
},
"About": {
"PartitionKey": "US",
"RowKey": "per-fb1de571-7142-47c8-bdb3-0eddd59f6ccd",
"FirstName": "George",
"LastName": "Martin",
"NickName": "Cowboy Hat",
"FullName": "George Martin",
"Description": "Ten gallons big.",
"ImageLocation": null,
"Region": "US"
},
"CommentDateTime": "2012-08-25T13:41:09.8899185Z"
}
Model (bound wrong from JSON, posted from debugging locals window). Another problem you'll notice here is that the "About" property is null. This should be a Person object, but Json.Net doesn't seem to be parsing this property, presumably because it's a type of interface rather than a class. Obviously here, it's a person that's being passed in that property in the JSON, but it could be something else, hence the use of an interface there:
comment {Classes.Comment} Classes.Comment
About null Classes.ICommentable
AboutKey US|per-fb1de571-7142-47c8-bdb3-0eddd59f6ccd string
CommentDateTime {1/1/0001 12:00:00 AM} System.DateTime
CommentText Testing Create. string
FromPerson {Classes.Person} Classes.Person
FromPersonKey US|per-4c3261d8-3b1a-4bd4-8850-4d769cfbd7ef string
PartitionKey US string
RowKey per-fb1de571-7142-47c8-bdb3-0eddd59f6ccd string
I have the following JSON structure which i get from a RestService:
{
"customer": {
"id": "123456",
[more attributes ....]
"items": [
{
"id": "1234",
},
{
"id": "2345",
}
[more items...]
]
}
}
which i successfully map into Core Data using RestKit. From another RestService (which i can not change) i then get more details to one single item in the items array. the JSON answer looks like
{
"customer": {
"id: "123456",
"item": {
"id": "1234",
"name": "foo",
[other attributes...]
}
}
}
Now the question: How can i map the second answer, so that the single item is added to the items array (or updated if it is already in there)?
Thanks for any ideas!
If you already know how to map JSON to Core Data, all that's left is just fetch theobject you want to add your item attributes to(using id or something else) and then just set it,rewriting the old one,or adding new fields.That's just general approach
If you set the appropriate primaryKeyAttribute of the RKManagedObjectMapping object you should be able to perform the mapping as you want it to.
It would actually be easier to help you, if you would post some of your mapping code, but this is how I meant it to be
Create the mapping for your customer object, defining all possible attributes and declare the mappingObject.primaryKeyAttribute = #"id"
Execute the mapping with the first request (or first answer as you put it)
After the first mapping step is finished execute the second request
This should initially create the customer objects you want and then update them.
I am looking for a library or framework that does JSON to Objective-C relational object mapping.
i.e. I need to map JSON containing objects, array of objects and dictionaries of objects to my custom objects.
something like:
DataObject {
"user" : {
"name":"Peter",
"id":1234
}
"place": "UK"
"job": {
"title" : "CTO",
"salary" : 1234567
}
"employess": [
{
"name":"Carlton",
"id":1235
},
{
"name":"Hugo",
"id":12346
}]
}
So there is a DataObject a UserObject and an employees array consisting of UserObjects.
I would like for the mapping from the JSON to my DataObject to happen "automatically", of course meant as I would like to describe the objects and there relations in the Object class and have the mapping done from this, instead of manually mapping each nested object.
(First level native objective-c properties are easily done with setValue:forKey and other KVO methods, but from there on it gets complicated).
I have been testing out RestKit but it seems there is no way to pick and choose which functionality you need from that framework, it is either all of it or none of it, and I do find it does too much for my needs.
Are anyone familiar with a library etc. out there that can do this?
Thank you in advance.
To map JSON to Objective-C objects, I have tried RestKit. I used it a while ago, so my criticisms might not apply anymore.
What I found out: nice idea. Not too complicated to plug-in. If it works, great for you. But if not, or if you need to push it a bit further, good luck to debug.
I regret the time I invested in it.
I am only looking for JSON to Objective-C objects, not the other way around.
I found a link on SO to JTObjectMapping - but can't find the original answer. Seems more lightweight and close to what I was searching, but I did not had the opportunity to try it.
An other similar class: jastor.
I prefer the approach of this two classes over RestKit, as it only takes care of one job, whereas RestKit tried to handle everything.
What you have posted above isn't valid JSON. If you made it valid JSON what you want to do is impossible without a specific schema, eg.
{
"DataObject": {
"user": {
"name": "Peter",
"id": 1234
},
"place": "UK",
"job": {
"title": "CTO",
"salary": 1234567
}
}
}
Is Dataobject a dictionary or an Object? What about User or Job? What is User is an instance of NSUser and job is an NSDictionary?
On the other hand, if you have a known schema:-
[
{
"class": "DataObject",
"properties": {
"user": {
"class": "User",
"properties": {
"name": "Peter",
"id": 1234
}
},
"place": "UK",
"job": {
"title": "CTO",
"salary": 1234567
}
}
}
]
you don't need a framework as it is trivial to map to your objects yourself once you have valid JSON. Pseudocode:-
createWithDict(dict) {
var newOb = create new(dict["class"]);
dict.properties.each( val, key ) {
if(val is dictionary && val.hasproperty("class"))
val = createWithDict(val)
newOb[key] = val
}
return newOb;
}