How to Deserialize a very Simple RestSharp JSON Object? - json

Forgive what surely has to be a dumb question, but I'm just starting out with C# using JSON.
I have this class:
public class DBCount
{
public string Count { get; set; }
}
I create an instance:
public DBCount dbCount;
My web service is returning this:
[{"Count":"234"}]
This code throws an invalid cast when it tries to deserialize the response:
var client = new RestClient("http://www.../")
var request = new RestRequest ("demo/jsondbcount.php",Method.GET);
request.RequestFormat = DataFormat.Json;
var response = client.Execute (request);
RestSharp.Deserializers.JsonDeserializer deserialCount = new JsonDeserializer();
dbCount = deserialCount.Deserialize<DBCount> (response);
Here's the invalid cast error:
"Cannot cast from source type to destination type"
If anyone can point me to a basic, simple example of using RestSharp to deserialize a simple object I'd be very grateful. I've searched everywhere for a basic code sample.
Thanks

You may have figured this out already but the problem is []. [{"Count":"234"}] is an array of size 1 that contains a single object with the field Count.
If you want your server to return an object that will deserialize to a DBCount then return {"Count":"234"} without the [].
If you want your code to correctly deserialize [{"Count":"234"}] then you need to indicate that it's deserializing a collection like so:
deserialCount.Deserialize<List<DBCount>>(response);

Related

deserialize json to object in netstandard1.0

I am trying to serialize a string that is returned from a http response and I am using netstandard1.0. Not a lot of serializing functions work in this framework, but I finally found a working function. Here is my code so far:
HttpResponseMessage Response = // initialized else where
var jsonTask = Response.Content.ReadAsStringAsync();
if (!jsonTask.IsCompleted) jsonTask.RunSynchronously();
string json = jsonTask.Result;
Data = JsonConvert.DeserializeObject<MyModel>(json);
However this does not deserialize I get from the http response. It throws an error that the DeserializeObject function is looking for a different format. When I run Result.Content.ReadAsStringAsync(), I get the result in the following format.
"[{\"key\":\"Password\",\"errors\":[\"The Password field is required.\"]},{\"key\":\"UserName\",\"errors\":[\"The UserName field is required.\"]},{\"key\":\"OrganizationUserName\",\"errors\":[\"The OrganizationUserName field is required.\"]}]"
Does anyone know how to deserialize this format?
If you define your MyModel as follows:
public class MyModel
{
public string key { get; set; }
public List<string> errors { get; set; }
}
You can deserialize as follows:
var list = JsonConvert.DeserializeObject<List<MyModel>>(json);
Notes:
I generated the c# definition for MyModel by uploading your JSON to http://json2csharp.com/.
The reason for the exception you are seeing trying to deserialize directly to MyModel is that your outer JSON container is an array, not an object. As explained in the standard, JSON has two types of container:
An array which is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
An object which is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).
In the Json.NET Serialization Guide: IEnumerable, Lists, and Arrays it is explained that JSON arrays are converted from and to .Net types implementing IEnumerable. So that's what you need to do.
If you know the array will contain no more than one element, you can use SingleOrDefault() to extract that single element:
Data = list.SingleOrDefault();
However, in the example included in you question, the outer array has 3 items, so this is not appropriate.
Sample fiddle.

Parse json and unable to access javascript object

I am passing a json object to the client side from java object with a time and value as attributes with gson
this.template.convertAndSend("/topic/123", gson.toJson(object, type));
and on the client side i have the following code where the json object data is stored in the body of the payload but I am unable to access the properties with obj.time or obj.value, it tells me undefined after it is parsed, I tried showing the entire 'obj' itself and the format seems fine however:
var subscription_callback1 = function(payload) {
var obj = JSON.parse(payload.body);
alert(obj);
};
output with alert(obj)
{"time":"3:00:34","value":"7989797"}
Nevermind solved. Since I am transfering STOMP protocol messages with the Spring 4 framework. I opted to use the Jackson2 message converter instead of directly using gson and it seems to work
#Configuration
#EnableWebSocketMessageBroker
public class MessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
messageConverters.add(new MappingJackson2MessageConverter());
return true;
}
then i directly put my java object into the send function instead of using gson to convert it as above
this.template.convertAndSend("/topic/123", event)

Create JSON Request string using Javascript Overlay types in GWT

We have used JSO for our JSON parsing in GWT client side. Now, we need to convert our Java objects to JSON string. I just wanted to understand, how we can achieve this? JSO overlay types was used for JSON parsing. Can it also be used to create a JSON request string or do we have to go by some other means?
Generating a JSON object in JavaScript is pretty simple. You can do it like this:
var obj = { "var1": "hello", "var2": "world" };
this will generate a JSON object with two varibles ("var1" and "var2") with their values ("hello", "world").
The Object can be converted into a String (for sending purposes) with the JSON.stringify(jso); method.
Generating JSON data from the java code isn't possible (well not with a usefull result) since all varibles are optimzed to single Strings, so applying this method wouldn't hava a usefull result (if even possible).
If you have already a JSO object (generated with something like safeeval). You can edit your varibles there, like this:
public final native void newValue(String newValue) /*-{
this.ValueName = newValue;
}-*/;
If you then want the object as string you have to define the following method in your JSO class:
public final native String returnAsString () /*-{
return JSON.stringify(this);
}-*/;
or use this in you Java class: String s = (new JSONObject(jso)).toString();.
This way you can edit your original intput data and send the original object back to the server.
BR

RestSharp deserialize JSON content(represent an object contains an byte array) error

The Client side receives a formal JSON content "{\"Id\":[1,2,3],\"Size\":56}", but get an error in deserialization the byte array.
1 Error occurs in the statement below
IRestResponse<key> response = client.Execute<key>(request);
2 Error message is "No parameterless constructor defined for this object."
3 The object class in client size is the same as it's in server side:
public class key
{
public byte[] id { get; set; }
public int Size { set; get; }
}
4 I've tried passing object that contains string and integer by JSON format and that's all fine but byte array.
JsonDeserializer from RestSharp can not deserialize array. Instead of byte[] use List<byte>. For more information see https://github.com/restsharp/RestSharp/wiki/Deserialization
I have run into this issue, too. My solution was to use RestSharp to perform a raw execute and use Json.NET to deserialize the result:
var response = client.Execute(request);
var keyResponse = JsonConvert.DeserializeObject<key>(response.Content);
keyResponse should now be an instance of your key class deserialized from the JSON content.
In addition to Chris Hogan's reply, I'd like to point out that I got this error when RestSharp incorrectly used the default serializer instead of the custom JSON.NET serializer I had assigned.
The reason for this was that I added a handler with content type application/json whereas the API I was getting the response from returned the content as text/json.
So by changing the AddHandler call to AddHandler("text/json", jsonDeserializer), I resolved the issue.

How to serialize this JSON Array String using Jackson Annotations?

[{"ID":"hzQ8ll","CreationDate":"Thu, 24 Feb 2011 12:53:31 GMT","Count":6,"Name":"SOMETAG"}]
The inside is of type Tag so I just wrote this Java class:
public class Tags {
public List <Tag>tags;
}
But I get com.sun.jersey.api.client.ClientHandlerException:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.test.Tags out of START_ARRAY token
I am using Jersey with the JacksonJsonProvider like this:
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(JacksonJsonProvider.class);
Then I just do a simple Jersey client call:
ClientResponse response = builder.get(ClientResponse.class);
Tags tags = response.getEntity(Tags.class);
Any ideas? Most of the time my outermost elements had a name associated to it so this is new to me. Thanks for any help
You possibly have to declare a Tag[] instead of a List<Tag>.
I had a similar issue with a different JSON library.
It seems to have to do with difficulties introspecting generic containers.
You have a strange usage of get().
http://jersey.java.net/nonav/apidocs/1.5/jersey/com/sun/jersey/api/client/UniformInterface.html#get%28java.lang.Class%29
Return and argument type should be the same.
Either:
ClientResponse resp = builder.get(ClientResponse.class);
or
Tag[] resp = builder.get(Tag[].class);
Anyway, it seems tha the problem is that your JSON data is an array and it is being deserialized into something that is not (Tags).
Try this directly:
Tag[] tags = response.getEntity(Tag[].class);