A rails service I am currently working on requires that points are returned as a GeoJSON object within our json response. We are using rgeo and the mysql2spatial adapter to represent these points in our application and I would like to use the rgeo-geojson gem to handle the encoding if possible (we already use it to decode geojson on post).
I am currently overwriting as_json with the following code to achieve this:
def as_json(params)
l = {:lat_lng => ::RGeo::GeoJSON.encode(lat_lng)}
self.attributes.merge(l).as_json
end
However this is not optimal as the root (eg object: {}) is missing. Is there a function to easily include it? (a lot of our models have a lat_lng associated, so I'd rather not hard code it).
Any tips for a ruby/rails beginner would be greatly appreciated
For posterity, I fixed this in the "rgeo-activerecord" gem, version 0.3.4, after getting several reports on it. By default it renders spatial columns in WKT. To switch it to GeoJSON, set this:
RGeo::ActiveRecord::GeometryMixin.set_json_generator(:geojson)
The answer by NielsV will work sometimes but not every time. Specifically, it will work for geographic factories (i.e. geometry columns in PostGIS) but not for GEOS-backed factories.
You can specify it by including root with this line of code:
ActiveRecord::Base.include_root_in_json = true
I Hope this helps.
I solved this by extending the RGEO library with an as_json method for a Point, doing this it's no longer required to overwrite as_json in my own models. Thanks for your response though.
module RGeo
module Feature
module Point
def as_json(params)
::RGeo::GeoJSON.encode(self)
end
end
end
end
Related
I get this error because I have circular references defined in my object model. My question is, is there any way to resolve this using one of the following two options?
Using Newtonsoft.Json and options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
Using System.Text.Json and options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
I'm not seeing a way to switch to Newtonsoft.Json in a Blazor WebAssembly application and I tried implementing option 2 in the ConfigureServices function of Startup.cs in my Server project but I still kept getting the error.
I'm just trying to find a solution that doesn't require me redefining my object model. The JsonIgnore attribute does not appear to be an option either because I assume, and it appears, that then any fields I define it on do not exist in the Json on the client which breaks my application.
Update: I found this site which looks to me like discusses exactly what I'm referring to here and how to implement the solution but I have not got it to work yet. If anyone is successfully using Blazor WebAssembly with circular references in your object model please let me know what you're doing.
https://github.com/dotnet/aspnetcore/issues/28286
Thank you for pointing out this error in Blazor. I found the answer in the issue you mentioned (this comment). You need to change json options also on the Client side. This works for me:
On server
services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
On client
var response = await Http.GetFromJsonAsync<T>("{Address}", new JsonSerializerOptions
{
ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve,
PropertyNamingPolicy = null
});
To the two options you mentioned there is a third option available if you use .NET 6 or above.
Using System.Text.Json and options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
Beware that ignoring cycles have issues on its own (such as data corruption) but if you were depending on it when you were using Newtonsoft.Json then you will be fine as it is basically the same behavior.
If you prefer to go with ReferenceHandler.Preserve, please share more info on what error you are getting and I can try to help you out.
One way to go about this is specify how much depth an object is allowed to have. Please see the documentation here regarding how to do this with System.Text.Json. I think this may help.
I am trying to find a clean way to access the regmap that is used with *RegisterNode for creating documentation and testing files. The TLRegisterNode has methods for generating the json through some Annotations. These are done in the regmap method by adding them to the ElaborationArtefacts object. Other protocols don't seem to have these annotations.
Is there anyway to iterate over the "regmap" Register Fields post elaboration or during?
I cannot just access the regmap as it's not really a val/var since it's a method. I can't quite figure out where this information is being stored. I don't really believe it's actually "storing" any information as much as it is simply creating the hardware to attach the specified logic to the RegisterNode based logic.
The JSON output is actually fine for me as I could just write a post processing script to convert JSON to my required formats, but I'm wondering if I can access this information OR if I could add a custom function call at the end. I cannot extend the case class *RegisterNode, but I'm not sure if it's possible to add custom functions to run at the end of the regmap method.
Here is something I threw together quickly:
//in *RegisterRouter.scala
def customregmap(customFunc: (RegField.Map*) => Unit, mapping: RegField.Map*) = {
regmap(mapping:_*)
customFunc(mapping:_*)
}
def regmap(mapping: RegField.Map*) = {
//normal stuff
}
A user could then create a custom function to run and pass it to the regmap or to the RegisterRouter
def myFunc(mapping: RegField.Map*): Unit = {
println("I'm doing my custom function for regmap!")
}
// ...
node.customregmap(myFunc,
0x0 -> coreControlRegFields,
0x4 -> fdControlRegFields,
0x8 -> fdControl2RegFields,
)
This is just a quick example I have. I believe what would be better, if something like this was possible, would be to have a Seq of functions that could be added to the RegisterNode that are ran at the end of the regmap method, similar to how TLRegisterNode currently works. So a user could add an arbitrary number and you still use the regmap call.
Background (not directly part of question):
I have a unified register script that I have built over the years in which I describe the registers for a particular IP. It works very similar to the RegField/node.regmap, except it obviously doesn't know about diplomacy and the like. It will generate the Verilog, but also a variety of files for DV (basic `defines for simple verilog simulations and more complex uvm_reg_block defines also with the ability to describe multiple of the IPs for a subsystem all the way up to an SoC level). It will also print out C Header files for SW and Sphinx reStructuredText for documentation.
Diplomacy actually solves one of the main issues I've been dealing with so I'm obviously trying to push most of my newer designs to Chisel/Diplo.
I ended up solving this by creating my own RegisterNode which is the same as the rocketchip RegisterNodes except that I use a different Elaboration Artifact to grab the info and store it for later.
I'm new to the Flutter (Dart) environment, so looking for some guidance on what I hope is a trivial coding issue on my side.
I have the following json, which I've validated,.....
[{"refModel":[{"firstName":"John","lastName":"Smith","os":"121212","refStatus":"Y","refActivationDate":"0000-00-00","gamesMiddles":0,"middles":[],"gamesLines":0,"lines":[],"gamesToReport":0,"reports":[]}]}]
The following is the class structure I use (not final version, needs further definitions).....
Data looks good after using json.decode (see below)
but when trying to map the data to the defined class, RefProfile, using the following....
setState(() {
refProfile = RefProfile.fromJson(refMap);
});
with following code generated by json_annotation.dart
the resulting refProfile.refModel list(array) contains 1 record but all fields are null.
I've been reworking the code based on reading stackoverflow and googling for suggestions for the past 3 days but no luck, so any insight would be appreciated!
as suspected, coding issue on my side. To make this work, I changed
refProfile = RefProfile.fromJson(refMap);
to
refProfile = RefProfile.fromJson(refMap['refModel']);
so the mapping script now properly finds the json object and maps the api data to the local model.
(Disclaimer: New to Rails here)
Say I have a Rails ActiveRecord Model that responds to "id":
User.first.id # => 22
My life has changed, and now I need to get this same object via JSON call, and I want minimal code changes.
I do this:
uri = URI.parse("http://localhost:3001/user/")
uri.query = "query=id#{user_id}"
#user = JSON.parse(open(uri).read)
I can now do:
#user["id"]
However, this is not good enough because it would mean too many changes.
Is there any way to turn this into a real User object? or something that will act like one in a simple one (I probably can create a dummy object with constructor, but I'm looking for something that will do it for me, and I suspect there is a simple Rails-way for it).
I have found a possible solution to this problem:
https://github.com/sprysoft/json_object
However, I realized I actually need the original ActiveRecord Model and not a dummy object..
That said, to my specific question, above gem is a possible solution.
I'm following the example of JTreeTable filesystem2 taken from the sun site http://java.sun.com/products/jfc/tsc/articles/treetable2/index.html#updating_the
My problem is that I can't update my model (and then my JTreeTable)...
In fact I create my model, I pass it to the JTreeTable and all work fine...but I need to modify the model...
I've yet answer a similar question, but now I've changed my code, without find a solution.
The problem is when and how I have to call the method fireTreeNodesChanged()...in the example above is used the method getPath() to retrieve information about the root node...but this is a method of File class..not my case...
Does anyone have a link to a simple code which shows how create a TreeTabelModel (with objects as nodes) and how update it?
FileBrowser is a good example of modeling a hierarchical file system as a tree. While its TreeModel is implemented using DefaultTreeModel, an alternative FileTreeModel is shown here. As mentioned in How to Use Trees: Creating a Data Model "the TreeModel interface accepts any kind of object as a tree node."