How to convert RealmResult to Json using Gson library - json

In this question How can I serialize a RealmObject to JSON in Realm for Java? The realm representative said that one can serialize realm object through GSON. Can you please explain it how?
I tried this.
RealmResults<Dog> myDogs=realm.where(Dog.class).findAll();
new Gson().toJson(myDogs);
But StackOverflowError occurred.

To make GSON serialization work with Realm you will need to write a custom JsonSerializer for each object that can be serialized and register it as a TypeAdapter.
You can see an example in this gist: https://gist.github.com/cmelchior/ddac8efd018123a1e53a

You get StackOverflow becouse of Gson based on reflection but managed object (RealmObjectProxy) have no real fields and fields of parent is nulls also some of proxy fields produses recursion in field type recognition of Gson it happens in $GsonTypes class.
To serialize RealmObject you can use one of this options:
Write your own adapter for every RealmObject childs which will takes data using getters.
Call realm.copyFromRealm(realmObject) before serialisation. It will looks like new Gson().toJson(realm.copyFromRealm(realmObject))
Use library based on 2nd option RealmSupportForGson
Hope it helps

The easier way is create a List<Dog> with RLMResult<Dog>, and then serialise this List with Gson.

After two days of bug resolve, I found this simple solution:
YourRealmObject realmObj = realm.where(YourRealmObject.class).findFirst();
if(realmObj != null) {
realmObj = realm.copyFromRealm(realmObj); //detach from Realm, copy values to fields
String json = gson.toJson(realmObj);
}

Related

Unity JSONUtility to JSON list of base classes

I have a BaseClass and bunch of derived classes.
I also have List<BaseClass> that contains objects from those derived classes.
When I do JSONUtility.ToJson(List<BaseClass>) I get only properties of BaseClass and not derived classes.
And well... I guess it is logical, but can't I force it to use derived class if there's a one or JSONUtility isn't capable of it? So I need to write custom logic for that?
Thanks!
Very probably JSONUtility.ToJson(List<BaseClass>) gets the elements you need with reflection, so the object returned is based on the incoming type.
I would try to obtain the jsons one by one and combine them in the logic, pre casting each of the types. Not tested nor debugged, just an starting point idea to move on:
string jsons;
foreach (var baseClass in baseClassList) {
Type specificType = baseClass.GetType();
string jsonString = JsonUtility.ToJson((specificType)baseClass)
jsons = "[" + string.Join(",", jsonstring) + "]";
}
I faced the same issue, to be honest JsonUtility is not good option for working with List.
My recommendations:
Use array instead of list with this helper class
or Newtonsoft Json Unity Package
I also needed JSON serialization, to call a REST json API, and I suggest to avoid JSONUtility.
It doesn't handle lists or dictionaries, as you saw.
Also it cannot serialize properties defined with { get; set; }, only fields, which is not blocking but not very convenient.
I agree with the recommendation above, just use Newtonsoft. It can serialize anything, and you will also benefit of the Serialization Settings (you can for example setup the contract resolver to convert all property names to snake_case...). See https://www.newtonsoft.com/json/help/html/SerializationSettings.htm

Serialize/deserialize a Dictionary with a comma-separated entry

I am developing a ASP.NET Core 3.1 website and I have data in a Dictionary<string, object> that I want to Serialize/Deserialize using Microsoft System.Text.Json (I am new to Json serialize/deserialize in fact). The data comes from a PostgreSQL DB query and one of the returned values is a comma-separated list of integers (converted to string) that results from the STRING_AGG function. The image below shows one of the entries of the Dictionary:
I serialize it using the following code. Please note that I have tried both Microsoft System.Text.Json and Newtonsoft.
jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(result);
//jsonResult = JsonSerializer.Serialize(result);
The data in the Dictionary should be deserialized according to the following class structure:
I use the following code:
//IEnumerable<SeccGralContenidoViewModel> seccGralContenido = JsonSerializer.Deserialize<IEnumerable<SeccGralContenidoViewModel>>(_seccGralContenidoRepository.Read());
IEnumerable<SeccGralContenidoViewModel> seccGralContenido = Newtonsoft.Json.JsonConvert.DeserializeObject <IEnumerable<SeccGralContenidoViewModel>>(_seccGralContenidoRepository.Read());
However, an exception is thrown when deserializing no matter if I use Newtonsoft or System.Text.Json:
I am originally using System.Text.Json namespace but I also tried using Newtonsoft. After analyzing a bit deeper, I see that the problem could be the way in which data is saved to the Dictionary but I have not found a workaround.
If you don't want to write a custom converter then the simplest solution is to introduce another property:
public string CategoriasContenidolds {get; set;}
private static char delimiter = ',';
[JsonIgnore]
public string[] CategoriasContenidolds_Collection
{
get => CategoriasContenidolds.Split(delimiter).Select(item => item.Trim()).ToArray();
set => CategoriasContenidolds = string.Join(delimiter, value);
}
The serializer will use the CategoriasContenidolds property during serialization and deserialization
You should use CategoriasContenidolds_Collection (or name whatever you want) in your business logic
By explicitly marking this property with JsonIgnore the serializer will ignore that
I could solve my issue by directly getting JSON formatted results from queries. PostgreSQL does an excellent job. This way I also avoid performing a 2-step process: first, getting the query result; second, serializing to JSON.

Serialize Object with PersistentCollection To JSON

I want to serialize entity object in my Symfony2 application to JSON object (I have to pass it to ajax function and use it in my javascripts).
Everything works fine but I have in my entity object addresses which are PersistentCollection object. Then if I serialize them in normal way field "adresses" has got empty Object. I figured out that I can set "LimitedRecursiveGetSetMethodNormalizer" to "1" and then PersistentCollection is being serialized. The problem is that I've got this object serialized, not array with my addresses so I can't use them in my javascript because they are not there...
\Cloud\ApplicationBundle\Resources\LimitedRecursiveGetSetMethodNormalizer::$limit = 1;
$businessJson = $this->get('serializer')->serialize($business, 'json');
Variable $business is of course Entity Object. I hope that my question is clear.
I have to add that I know that i can convert PersistentCollection object to Array and then serialize it to Json but this way i would have to pass my entity and adresses in seperate variables. I would prefer to do it one variable.
Thanks for any help !

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 ;)

Accessing request parameters from registerObjectMarshaller() in BootStrap

I am marshaling objects in Grails to JSON using the JSON.registerObjectMarshaller() method, which is invoked in the BootStrap class.
My object graph has a number of nested objects e.g. User -> Address -> Phone and I have a marshaller for each object.
I have a scenario where I want to be able to either return a "shallow" or "deep" version of the top level object. In the case of a shallow request, in place of the address I want to return the field. In the case of the a deep version, the other object marshalers can do delegated to as usual.
I want to do a deep versus shallow based on the value of a parameter passed in the request, however I do not know how to access request parameters when in the registerObjectMarshaller() method from the BootStrap class.
Once I have a way to access these parameters I can tailor it as needed.
Any pointers would be greatly appreciated.
I once tried the object marshaller approach for XML and sadly it didn't work out.
Similar to you, I don't have one way to represent objects. I have a lot more than two, but I think Object Marshallers are a way to go only if you want to do something trivial. If you need more, just forget about them.
It may be much easier for you, to simply create a service or a class with static methods which will generate the JSON for you based on the values you pass.
You can use JsonGroovyBuilder to achieve that, and then just convert it to string and wrap it in a nice http header or whatever you need.
In my case it looks like this [mind you, this is for XML, so you have to use JsonGroovyBuilder, or other - whichever suits you - and you will probably not need to use the StringWriter as I do]:
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
def retData = someService.doSomething()
def xmlGen = new XmlResponseGenerator(xml, retData)
render(contentType: 'text/xml', encoding: "UTF-8", text: writer.toString())