I need to deserialize this, which is encoded in JSON and I can not, I need it, anyone can help me?
[{"idReservation":2560,
"startDate":"30/09/2013 09:00",
"endDate":"30/09/2013 09:10",
"timeOut":"24/09/2013 16:02:23",
"idResource":1477,
"resourceDescription":"Profesional",
"players":
[{"idPlayer":283,
"idCustomer":2,
"name":"Ignacio",
"image":"/public/images/interface/customer/user.png",
"total":0}],
"anulable":true,
"name":"Ignacio",
"price":0,
"status":"Reservada",
"parententityname":"",
"idparententity":"",
"unixTime":1380524400},]
greetings and thank you very much
As #YuriyGalanter suggests Json.NET will do the job, it has great performance and avoids the problem you get when trying to serialise a javascript datetime object to .net datetime object.
The documentation provides an example of how to deserialise an object.
Expanding on Mr Shoubs' answer:
1) Download the Json.Net DLL per Mr Shoubs' answer.
2) Add a reference to this DLL in your Visual Studio Project.
3) Create a VB Reservation class that you want to end up with:
Public Class Reservation
Public Property idReservation() as Integer
Public Property startDate() as Date
...
End Class
Make the spelling and casing exactly as they are in the JSON object to keep things simple.
4) Declare an object of type Reservation and populate it with the JSON string you have - using the DeserializeObject method:
Dim obj As Reservation
obj = JsonConvert.DeserializeObject(Of Reservation)(yourJsonString)
obj should now contain the data you want.
Related
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
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.
Here is my situation:
I have a form that is collecting a list of items in a textarea as a JSON Object.
The form textarea looks like this:
<textarea id="listItems">
[
{"id":"1","name":"apple"},
{"id":"2","name":"orange"},
{"id":"3","name":"banana"}
]
</textarea>
I need to be able to parse that string and POST each item into a SQL Table.
ItemID | ItemName
-----------------
1 | apple
2 | orange
3 | banana
I don't think I have a good understanding of using the JavaScriptSerializer Class. I'm using VB.net
I don't have any server-side code yet but I know that I have to parse out the JSON string and then loop through it and then save each item.
Couldn't I just convert the JSON string into a DataTable and then loop through that temporary table?
Not sure. I'm trying to figure this out but some help would be useful.
Also I'm referencing a few SO posts to see if maybe I can figure this out
This one
This one
So expecting the following Json Object at the Server
[
{"id":"1","name":"apple"},
{"id":"2","name":"orange"},
{"id":"3","name":"banana"}
]
you would be able to do this:
Public Function DoSomething()
Dim jsonObject = "[{""id"":""1"",""name"":""apple""},{""id"":""2"",""name"":""orange""},{""id"":""3"",""name"":""banana""}]"
Dim obj = New JavaScriptSerializer().Deserialize(Of TestObject())(jsonObject)
End Function
With this Model
Public Class TestObject
Public Property id As Integer
Public Property name As String
End Class
At runtime you will have an array of Objects in obj which you can then manipulate and fill into a DataTable or directly feed to the Database. Converting the Json into an Object is not the only option you have here but it is a convenient one.
Since you did not specify the context you are working in it is a little unclear what might be the best solution to your case. Maybe you want to do a little research on different Json Frameworks (for example Json.net) as well as Data-Handling with Databases so you get ideas about the how and when.
This was the best answer I found and I adjusted it to meet my needs.
I've also included the link to the duplicate POST that answered my question.
I'm also referencing another similar post which has a similar situation.
This is the link to the .Net Fiddle that demonstrates what I was looking for.
DEMO
How to deserialize JSON which can be an array or a single object
How to handle both a single item and an array for the same property using JSON.net
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);
}
I was wondering if someone could suggest the recommended way to covert flat JSON into a complex java object.
Example JSON
{account_id: 1, user_id:3, user_name:john ... }
But my java class needs to be
class Account {
int account_id;
User user;
}
And here is the user object...
class User {
int user_id;
String user_name;
}
It looks like I could go from JSON to java using the Jackson constructor to create the object the way I need but I also need to covert the java object into a flat JSON.
Do I need to use a serializer/deserializer for each class or is there a way I can do it with simple annotations... By maybe telling it to ignore the user object but not what's inside it..
Let me know what your ideas are. Thanks