JSON column passed to view as string - Laravel - Vuejs2 - json

I'm passing a Laravel Model's dataset to a vuejs2 component via ajax/ axiom and rendering it fine.
However, there is a JSON column in the model which stores a valid json object, the data could look like so: {'key':'value'} and it's worth noting that I'm working with it without issue in Laravel Controllers etc thanks to a Mutator on the Model ( protected $casts = [ 'the_json_column' => 'array']; )
When I pass this model to vuejs via axiom / ajax all of the properties in the array behave as usual, I can iterate over them and render them in the vuejs2 component DOM.
Until I interact with 'the_json_column' which despite Laravel's mutator is being passed to vuejs2 as a string, e.g. "{'key':'value'}"
Is there a more elegant way than doing a JSON.parse(data.the_json_column).key in my vuejs2 component every time I want to interact with the JSON column data?

The solution I've gone with is decoding the data property manually in the VueJS2 template,
e.g. JSON.parse(data.key_which_is_actually_json).property_in_the_object
Any laravel based code (accessors, mutators etc) will fail when the property is transferred to VueJS2 component over HTTP as VueJS2 isn't smart enough to check properties in data receive and decode them.
VueJS2 seems to only decode the top level of properties in data received.

You may create your own Accessor and then convert the column to an array manually before retrieving the model.
public function getTheJsonColumnAttribute($value)
{
return json_decode($value, true);
}
While it may seem laravel simply treated that column as a mere 'string' value when coming out, you can further validate that there is indeed a conversion.

Related

Is there an elegant way to get JSON Data from OdataV4 Model in Openui5?

(openui5 Version 1.42)
Hello,
I have a list of items, whose data is provided by an odatav4 model (sap.ui.model.odata.v4.ODataModel)
When I select an Item, I bind it to a detail view with its own controller.
Now I would like to get the data from the odata model.
This solution does not work, as the odata v4 model does not support the read method:
Converting ODataModel into JSON Model
Is there a way to get the data of the selected entry as json (model or directly as data)?
What I can get is a property from the context in my controller:
this.getView().getBindingContext("ams").getProperty("Ident)
returns 1. The Identifier of my selected entry.
If you call the method getObject on the binding context you should get the entity as json.
this.getView().getBindingContext("ams").getObject()
You can use Context.getObject. This delivers the complete object that the context points to. However there is a bug in 1.42; the result is wrapped and you have to access it via .value[0]. This bug has been fixed in 1.44.7. See the release notes.
A solution that works in 1.42 and all following releases is to make use of the fact that getObject also can deliver parts of the object. Deliver an empty sPath parameter:
this.getView().getBindingContext("ams").getObject("")

Grails, create domain object from json-string with has-many relation

I'm trying to parse a grails parameter map to a Json String, and then back to a parameter map. (For saving html form entries with constraint-violations)
Everything is fine as long as there is no hasMany relationship in the parameter-map.
I'm using
fc.parameter = params as JSON
to save the params as JSON String.
Later I'm trying to rebuild the parameter map and create a new Domain-Object with it:
new Foo(JSON.parse(fc.parameter))
Everything is fine using only 1:1 relationships (states).
[states:2, listSize:50, name:TestFilter]
But when I try to rebuild a params-map with multi-select values (states)
[states:[1,2], listSize:50, name:TestFilter]
I'm getting this IllegalStateException:
Failed to convert property value of type org.codehaus.groovy.grails.web.json.JSONArray to required type java.util.Set for property states; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [de.gotosec.approve.State] for property states[0]: no matching editors or conversion strategy found
I tried to use this, but without success:
JSON.use("deep") {
new Foo(JSON.parse(fc.parameter))
}
You can use JsonSlurper instead of the converters.JSON of grails, it maps JSON objects to Groovy Maps. I think this link also might help you.
Edit: Now, if the problem is binding the params map to your domain, you should try using bindData() method, like:
bindData(foo, params)
Note that this straightforward use is only if you're calling bindData inside a controller.
What seems to be happening in your case is that Grails is trying to bind a concrete type of List (ArrayList in the case of JsonSlurper and JSONArray in the case of converters.JSON) into a Set of properties (which is the default data structure for one-to-many associations). I would have to take a look at your code to confirm that. But, as you did substitute states: [1,2] for a method of your app, try another test to confirm this hypothesis. Change:
states:[1,2]
for
states:[1,2] as Set
If this is really the problem and not even bindData() works, take a look at this for a harder way to make it work using object marshalling and converters.JSON. I don't know if it's practical for you to use it in your project, but it sure works nicely ;)

How to serialize transient fields in the model via FlexJson?

I am using Play Framework to expose REST API, which returns some JSON objects.
To simplify the API usage, I would like to return a "calculated" field in the response.
Unfortunately, in my tests, while FlexJson does not ignore the transient model fields completely, but always sets them to 'null'.
More details:
In the model class, I define:
#Transient
public String currencyName;
The only constructor of the class set the value to "dollar" (for debugging purposes):
this.currencyName = "dollar";
When serializing the class using FlexJson, when the 'currencyName' field is not specified in the include/ exclude - the result always looks like:
"currencyName":null
Any idea what got wrong, and how to get the field value serialized into JSON?
Thanks in advance.
By definition if your field is transient it will not be serialized. Perhaps this field should not be transient in your application if the state matters.

Parsing JSON objects of unknown type with AutoBean on GWT

My server returns a list of objects in JSON. They might be Cats or Dogs, for example.
When I know that they'll all be Cats, I can set the AutoBeanCodex to work easily. When I don't know what types they are, though... what should I do?
I could give all of my entities a type field, but then I'd have to parse each entity before passing it to the AutoBeanCodex, which borders on defeating the point. What other options do I have?
Just got to play with this the other day, and fought it for a few hours, trying #Category methods and others, until I found this: You can create a property of type Splittable, which represents the underlying transport type that has some encoding for booleans/Strings/Lists/Maps. In my case, I know some enveloping type that goes over the wire at design time, and based on some other property, some other field can be any number of other autobeans.
You don't even need to know the type of the other bean at compile time, you could get values out using Splittable's methods, but if using autobeans anyway, it is nice to define the data that is wrapped.
interface Envelope {
String getStatus();
String getDataType();
Splittable getData();
}
(Setters might be desired if you sending data as well as recieving - encoding a bean into a `Splittable to send it in an envelope is even easier than decoding it)
The JSON sent over the wire is decoded (probably using AutoBeanCodex) into the Envelope type, and after you've decided what type must be coming out of the getData() method, call something like this to get the nested object out
SpecificNestedBean bean = AutoBeanCodex.decode(factory,
SpecificNestedBean.class,
env.getData()).as();
The Envelope type and the nested types (in factory above) don't even need to be the same AutoBeanFactory type. This could allow you to abstract out the reading/writing of envelopes from the generic transport instance, and use a specific factory for each dataType string property to decode the data's model (and nested models).

Create a List-type view dynamically from a Json object in MVC3

I have a controller that access a WCF service which returns a Json object (collection). All rows are of same type, but at different calls the row stricture is different (the return object comes from a user-built sql query, executed with executeReader and serialized as Json
So I don't know the row structure upfront.
What I need is an easy way to pass this Json string to something which will generate a view of type list on the fly for it. Doesn't matter formatting, etc, just should be output easily as a table.
Does anyone knows how can I accomplish this?
Another option might be to have something that generate the view on the fly for a IEnumerable of anonymous objects (since using this I could convert the json to a list of anonymous)
EDIT
I found something that does pretty much what I need, except it display metadata about passed object.
It is preetyPrint.js, and I integrated it in my page as below:
In my controller I set the result json object to ViewBag.Result, and in the view I used this code:
<script src="#Url.Content("~/Scripts/prettyprint.js")" type="text/javascript"> </script>
<div id="resultGrid"></div>
<script>
var resultObject = #Html.Raw(ViewBag.Result);
var ppTable = prettyPrint(resultObject);
document.getElementById('resultGrid').appendChild(ppTable);
</script>
Does anyone knows such script that actually "dump" the data instead of metadata?
Thanks.
You should create a class to deserialize to if you know the properties of the row. Then use the JavaScriptSerializer class to deserialize to a list of your new class you created. Then you can take a look at the WebGrid class to output the HTML, or just manually iterate over the property metadata in your view.
Creating a custom class will provide you the ability to use metadata to control formatting or other display attributes of the output.
If you cannot create a custom class, you can always use Json.NET or the JavaScriptSerializer to deserialize to a list of dictionary objects or ExpandoObject / Dynamic's or something. Then you would have to manually write something to iterate the keys I think. The ModelMetadataProvider in MVC may be able to handle these allowing you to just iterate the properties in your view code.