Matt Matt - 4 months ago 15
Java Question

Parsing a Single Integer with Json Net

I am trying to parse a simple long integer with Json.Net. This is what the response looks like:


Transfer-Encoding: chunked
Date: Fri, 03 Jul 2015 16:15:33 GMT
Server: Apache-Coyote/1.1
Content-Type: application/json

body is simply: 1435775316000

In gson library with Java, I can parse it like this:

Long one = gson.fromJson("1435775316000", Long.class);

I have a method in my .Net client to parse responses, but it expects it to be in Json format:

private static JObject sendRequest(String params)

HttpResponseMessage response = Client.GetAsync(params).Result;

if (response.IsSuccessStatusCode)
var jsonResponse = response.Content.ReadAsStringAsync().Result;
return JObject.Parse(jsonResponse);
//do something else
catch (Exception e)

this works fine if the response was in Json mapped format:
{ "version" : "1435775316000" }

but the service simply returns:

Again, the header of the response says it's in Json. How do I allow this with the Json.Net library.

I probably should have asked what is the correct way of arguing my case. The developer on the service end says returning an integer is ok, arguing that it's more work for the service implementation, and would have to create a json object. I disagree, and believe that it should return a proper json object, like every other call to said service. How can I convince the service developer to do so? Am I asking too much? I mean, it is easier on the service end to return a simple int, but that means that on my end I have to check whether or not to parse it as an object, or a token json value.


If the service just returns "1435775316000" then that isn't really JSON - or at least, it's not a JSON object, which is at least a rather more widely-used approach to returning JSON. You can just parse it with long.Parse:

long value = long.Parse(jsonResponse);

If you really need to create a JObject from that, you can easily do so:

JObject wrapped = new JObject(value);

... but I'd question whether it's really a good idea.

Another option is to understand it as a JSON value though. You could change your method to return JToken, and use:

return JToken.Parse(jsonResponse);

Here's an example showing that working:

using System;
using Newtonsoft.Json.Linq;

class Test
    static void Main(string[] args) 
        var jsonObject = "{ \"name\": \"foo\" }";
        var jsonLong = "123456";
        Console.WriteLine(JToken.Parse(jsonObject).GetType()); // JObject
        Console.WriteLine(JToken.Parse(jsonLong).GetType()); // JValue