When I'm seralize array I've got something like this:
{"0":{"id":1,"name":"Kowalscy","familyMembers":[{"id":1,"familyMemberType":1,"user":{},"name":"Pawel","isAdmin":true,"notes":[],"email":""},{"id":2,"familyMemberType":2,"user":{},"name":"Mama Koper","isAdmin":false,"notes":[],"email":""}],"children":[]},
"1":{"id":2,"name":"Spiochy","familyMembers":[{"id":3,"familyMemberType":2,"user":{},"name":"Test Nowak","isAdmin":false,"notes":[],"email":""}],"children":[]}, .....
But I have problem with deseralization that array using JSON, I think that it should look like:
[{object}, {object}]
Is there way to change that?
Here is my code from symfony2
$result = $serializer->serialize($families, 'json',SerializationContext::create()->setGroups(array('getFamilies')));
EDIT:
I've found that "getArrayResult()" returns array, but it doesn't contain my relation entity
From memory, it is a bad practice to have an array as top level in json.
What are "top level JSON arrays" and why are they a security risk?
Moreother, if you use array, you lost the ids of your objects. So it is normal that you lost relations.
Related
I'm trying to find the vocabulary to describe what I want and if it exists.
I have a table that shows a few data points from large objects. Loading the entire objects just for the table is very slow. Is there a way to only pass to the front the few properties I want without having to define a new object?
I found something called Sparse Fieldsets in JSON API, and I'm wondering if something like this exists for .NET under another name.
Update:
Talking to another coder, I realize it probably makes more sense to implement something like this between the backend and the database and make a specific call for this table. I still need to work out if I need to create a new object to support this. I think it'd still be faster if I just kept the same object but nulled out all of the connecting objects that I don't need for the table. But maybe that's considered bad practice? Also we're using Entity Framework for what it's worth.
Update 2:
I just created a new query without all of the .Include() and works well enough for what I need:
_dataContext.ApplePie
.Include(f => f.Apples).ThenInclude(f => f.Apple)
.Include(f => f.Sugars).ThenInclude(f => f.MolecularStructure)
.Include(f => f.Recipe)
Maybe you are looking for Anonymous Types?
For example, if you had a typed object with three properties, but you only wanted to operate on two:
var threePropThing = new ThreePropertyThing { Id = 1, Message = "test", ExtraProperty = "ex" };
var myAnonThing = new { Id = threePropThing.Id, Message = threePropThing.Message };
Best practice would be to not pass this anonymous object around. But, if you really needed to, you could return it as type object.
Typically, when passing data around in c#, you want to have it typed.
C# is a strongly-typed language and I would say that it is unusual for C# to support scenarios, when object definition (properties) are not known in advance, like in JSON API "fields" parameter case. Implementing this would imply using reflection to filter the properties, which is usually slow and error-prone.
When implementing C# web-services, people usually create one DTO response model per each request.
If your table has fixed set of fields, I would personally recommend to create a DTO class containing only the fields which are required for your table, and then create a method which returns this response for your specific request. While it doesn't align with "without having to define a new object" in the question, it makes the intention clear and makes it really easier to maintain the API in future.
You might want to use libraries like AutoMapper to save time and avoid duplicated code of copying the values from data model to DTO, if you have many such methods.
I'm using the .NET API of CosmosDB and I'm getting a hard time trying to figure out how to get the raw result of a CosmosDB query prior to it getting deserialized into a class. Browsing the documentation, all examples I find cast the results to an specific class or to a dynamic. That is:
//This returns a Document, wich actually is a dynamic...
client.ReadDocumentAsync(...)
//This returns an object of type MyClass, wich I supose is casted internally by the API
client.ReadDocumentAsync<MyClass>(...)
What I want to do is to get the original raw JSON payload of the result to inspect it without the overhead of deserializing it to anything else.
Does anybody know if it's possible to get the raw result with the .NET api? If so, how?
In other cases, I need to use the result as an ExpandoObject to treat it dynamically, but I find that the "dynamic" results given by the api are not "expandables" so I'm forced to serialize them and then deserialize again in a recursive form into an ExpandoObject. Furthermore, the result is polluted with _rid, Etag, etc. properties that I don't need on my object. It's quite anoying.
I think it's an unnecesary overhead to serialize and then deserialize again, so maybe the optimus way would be to get the raw JSON result and write a method to deserialize directly to Expando.
Or maybe I'm loosing any point and there's an API to get the results as Expandos. Does anybody know it?
Check out this question that I had earlier:
Converting arbitrary json response to list of "things"
Altough I didn't named it, the API in question was actually DocumentDb, so I think you'll be able to use that code.
Seen some bad advice here, but it is built into the SDK natively.
Document doc = cosmosClient.ReadDocumentAsync(yourDocLink);
string json = doc.ToString();
I am building an app with Symfony.
I've got a Doctrine entity that contains (among other properties) a collection of another Entity (forming a OneToMany association).
Class OuterEntity
{
/**
* #ORM\OneToMany(targetEntity="InnerEntity", mappedBy="outer", cascade={"persist", "remove"})
*/
private $inners;
}
In my OuterEntityController, in the updateOuterEntityAction method, i do the following :
parse the request
get the updated Outer from db
modify it according to the request
call flush() on the entity manager
call findAll() on the OuterEntity repository
return the OuterEntity list to the client in a JsonResponse in order to notify it of the new state of the db. Since I use a JsonResponse, I let Symfony do the serialization (very probably with json_encode).
Everything is allright except when I delete one or more InnerEntity in the association. The issue does not come from the removal, but from the returned json format. Most of the times, the inners I get are under the form of a simple array:
{"inners":[{inner1},{inner2},...]}
, which is fine for me. But after a removal from this association (in the example, I assume the 2nd one was deleted), I get an array like this:
{"inners":{"0":{inner1},"2":{inner2},"3":{...},...}
Furthermore, this issue doesn't happen if the last Inner is deleted (or several Inners all located at the end of the array).
My supposition is that Doctrine places the association in an associative array and when json_encode serializes this array, it renders in the first format if the indexation is normal (0, 1, 2...), or in the second format if the indexation is broken (0, 2, 3...).
So my question is now : why doctrine does not place the result in a "normally indexed" array after a removal?
I think there's something going on with Doctrine's caching mechanism, but I can't figure exactly what. Maybe it's because the entity manager still considers the deleted entities. But I thought that the entity manager was cleared after the flush, isn't it?
I tried to call clear() on the entity manager, but I've had some strange behaviour and quickly gave up.
I'd be glad if one of you could point the mistake I am making.
It seems that the problem is on my side of the keyboard.
I don't know why, but I retried to clear the entity manager today, and everything works just fine as I first expected. I must have made a really dumb move at my first try.
Thanks everybody for the help, and sorry for the inconvenience.
I have some personal data structure mixed with "standard fields". I would like to avoid the manual work on simple fields (with datastore native API):
toPersist.setProperty("field1", value1);
toPersist.setUnindexedProperty("field2", value2);
but I still want to get the prefilled Entity instance toPersist so I can add my own #Ignore fields my self
For example:
Entity filled = OfyService.ofy().save().entity(this).fill();
filled.setProperty("mySpecialField", jsonValue);
//...
// I want to save my entities alone
datastore.put( filled );
reversely I'd like to get the Entity object representing each entry in a load() call.
Is this possible? or do I have to dive into Objectify code to hack it?
thanks for your answers
I don't follow your question exactly, but I'm pretty sure what you're looking for are the #OnLoad and #OnSave annotations. You add them to methods within your entity classes, and those methods will be called just after an entity is loaded, or just before one is saved, respectively. The documentation for them is here.
Edit:
After your comments (below) I now understand what you are trying to accomplish. Yes, Objectify supports this (though I have never tried it myself). You want to use the Saver.toEntity() and Loader.fromEntity() methods. It appears you can use them like this:
// Use Objectify to convert a POJO into an Entity
Entity filled = ofy().save().toEntity(myPojo);
// Use Objectify to convert an Entity into a POJO
Object pojoCopy = ofy().load().fromEntity(filled);
I know that it is possible to specify that you want array type instead of object type when you run query with Doctrine. However, I happen to be working with the code that I can't edit which returns to me the result from a query as an object and I want to be able to convert that to array somehow. It seems like in the older version doctrine used to have something like toArray() which can be used.
Is there something similar to that now which I can use?
No, doctrine 2 uses the data mapper pattern and doesn't make any assumptions about the PHP class. If the class doesn't provide a toArray() method explicitly, then you'd need to create the array manually with the object's getter methods.