2

I'm trying to parse the JSON string using java. I don't know How to do that, I searched lot in internet and I got some idea. With that I have build code, but it doesn't work. When try to execute my code it throw an error. I couldn't solve the error.

See below is my Code:

import java.util.*;
import java.io.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JSOnNStringParsing {

    public static void main(String[] args) {        
        try
        {
            BufferedReader read=new BufferedReader(new FileReader("D:\\Kavi works\\OutputFiles\\JSON_String.txt"));
            String line=read.readLine();
            while(line!=null)
            {
                System.out.println("Line = "+line);
                JSONParser jsonParser = new JSONParser();
                JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
                System.out.println("Read : "+jsonObject.get("read"));
                JSONArray network = (JSONArray) jsonObject.get("network");
                Iterator<String> iterator = network.iterator();
                while (iterator.hasNext()) {
                    System.out.println(iterator.next());
                }
            }
        }
        catch(Exception e)
        {
            System.out.println("Error occured :"+e);
        }
    }
}

My JSON string is in that file:

{"read":"2015-05-07T19:30:48.165009273+05:30","network":{"rx_bytes":11124,"rx_packets":116,"rx_errors":0,"rx_dropped":0,"tx_bytes":648,"tx_packets":8,"tx_errors":0,"tx_dropped":0},"cpu_stats":{"cpu_usage":{"total_usage":157158138204,"percpu_usage":[157158138204],"usage_in_kernelmode":49530000000,"usage_in_usermode":58420000000},"system_cpu_usage":258964110000000,"throttling_data":{"periods":0,"throttled_periods":0,"throttled_time":0}},"memory_stats":{"usage":73969664,"max_usage":74600448,"stats":{"active_anon":73928704,"active_file":4096,"cache":86016,"hierarchical_memory_limit":18446744073709551615,"inactive_anon":4096,"inactive_file":32768,"mapped_file":32768,"pgfault":62880,"pgmajfault":0,"pgpgin":34656,"pgpgout":34482,"rss":73883648,"rss_huge":67108864,"total_active_anon":73928704,"total_active_file":4096,"total_cache":86016,"total_inactive_anon":4096,"total_inactive_file":32768,"total_mapped_file":32768,"total_pgfault":62880,"total_pgmajfault":0,"total_pgpgin":34656,"total_pgpgout":34482,"total_rss":73883648,"total_rss_huge":67108864,"total_unevictable":0,"total_writeback":0,"unevictable":0,"writeback":0},"failcnt":0,"limit":2099310592},"blkio_stats":{"io_service_bytes_recursive":[],"io_serviced_recursive":[],"io_queue_recursive":[],"io_service_time_recursive":[],"io_wait_time_recursive":[],"io_merged_recursive":[],"io_time_recursive":[],"sectors_recursive":[]}}

When I execute my code it throws an error like below:

Line = {"read":"2015-05-07T19:30:48.165009273+05:30","network":{"rx_bytes":11124,"rx_packets":116,"rx_errors":0,"rx_dropped":0,"tx_bytes":648,"tx_packets":8,"tx_errors":0,"tx_dropped":0},"cpu_stats":{"cpu_usage":{"total_usage":157158138204,"percpu_usage":[157158138204],"usage_in_kernelmode":49530000000,"usage_in_usermode":58420000000},"system_cpu_usage":258964110000000,"throttling_data":{"periods":0,"throttled_periods":0,"throttled_time":0}},"memory_stats":{"usage":73969664,"max_usage":74600448,"stats":{"active_anon":73928704,"active_file":4096,"cache":86016,"hierarchical_memory_limit":18446744073709551615,"inactive_anon":4096,"inactive_file":32768,"mapped_file":32768,"pgfault":62880,"pgmajfault":0,"pgpgin":34656,"pgpgout":34482,"rss":73883648,"rss_huge":67108864,"total_active_anon":73928704,"total_active_file":4096,"total_cache":86016,"total_inactive_anon":4096,"total_inactive_file":32768,"total_mapped_file":32768,"total_pgfault":62880,"total_pgmajfault":0,"total_pgpgin":34656,"total_pgpgout":34482,"total_rss":73883648,"total_rss_huge":67108864,"total_unevictable":0,"total_writeback":0,"unevictable":0,"writeback":0},"failcnt":0,"limit":2099310592},"blkio_stats":{"io_service_bytes_recursive":[],"io_serviced_recursive":[],"io_queue_recursive":[],"io_service_time_recursive":[],"io_wait_time_recursive":[],"io_merged_recursive":[],"io_time_recursive":[],"sectors_recursive":[]}}
Error occured :java.lang.NumberFormatException: For input string: "18446744073709551615"

Please help me to solve this issue, Thanks in advance

Kavi Chinna
  • 237
  • 2
  • 7
  • 18

3 Answers3

5

That looks like it's a bug in JSON-simple to me. Using the org.json parser, it works fine.

The problem is that it's trying to parse the value as an integer and it's outside the range of normal Java primitive integer types. It could parse it as a BigInteger instead, or as a double (which would be more in-keeping with JSON not actually distinguishing between integers and floating point values).

If you add a .0 to the end of the value in the JSON, it works fine in JSON-simple, but in my view you shouldn't have to do that.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • "In my view you shouldn't have to do that"--agree completely. Since this input is coming from a file, I'd consider any solution that requires changing the input file (or other external input source) to be a non-solution. – ajb May 12 '15 at 06:30
  • Any workaround on this issue, I am getting the exact same error. I am not able to put .0 at the end as the JSON data is coming from a log file which I need to parse. – Kushal Shinde May 26 '18 at 16:34
  • @KushalShinde I think the workaround would be to use a better parser... – Jon Skeet May 26 '18 at 21:15
  • @JonSkeet Thank you. I switched to gson and my problem got resolved. – Kushal Shinde May 26 '18 at 22:09
1

Your json is wrong to parse in Java. The maximum value of Long is 9223372036854775807 in Java but in your json you are exceeding it. Json can access really really long numbers, but java won't.

Just change number types in json as String after that you are good to go. Look at the following example.

{
  "read": "2015-05-07T19:30:48.165009273+05:30",
  "network": {
    "rx_bytes": 11124,
    "rx_packets": 116,
    "rx_errors": 0,
    "rx_dropped": 0,
    "tx_bytes": 648,
    "tx_packets": 8,
    "tx_errors": 0,
    "tx_dropped": 0
  },
  "cpu_stats": {
    "cpu_usage": {
      "total_usage": 157158138204,
      "percpu_usage": [
        157158138204
      ],
      "usage_in_kernelmode": 49530000000,
      "usage_in_usermode": 58420000000
    },
    "system_cpu_usage": 258964110000000,
    "throttling_data": {
      "periods": 0,
      "throttled_periods": 0,
      "throttled_time": 0
    }
  },
  "memory_stats": {
    "usage": 73969664,
    "max_usage": 74600448,
    "stats": {
      "active_anon": 73928704,
      "active_file": 4096,
      "cache": 86016,
      "hierarchical_memory_limit": "18446744073709552000898498494949849849849849849849849849841998498498484984",
      "inactive_anon": 4096,
      "inactive_file": 32768,
      "mapped_file": 32768,
      "pgfault": 62880,
      "pgmajfault": 0,
      "pgpgin": 34656,
      "pgpgout": 34482,
      "rss": 73883648,
      "rss_huge": 67108864,
      "total_active_anon": 73928704,
      "total_active_file": 4096,
      "total_cache": 86016,
      "total_inactive_anon": 4096,
      "total_inactive_file": 32768,
      "total_mapped_file": 32768,
      "total_pgfault": 62880,
      "total_pgmajfault": 0,
      "total_pgpgin": 34656,
      "total_pgpgout": 34482,
      "total_rss": 73883648,
      "total_rss_huge": 67108864,
      "total_unevictable": 0,
      "total_writeback": 0,
      "unevictable": 0,
      "writeback": 0
    },
    "failcnt": 0,
    "limit": 2099310592
  },
  "blkio_stats": {
    "io_service_bytes_recursive": [],
    "io_serviced_recursive": [],
    "io_queue_recursive": [],
    "io_service_time_recursive": [],
    "io_wait_time_recursive": [],
    "io_merged_recursive": [],
    "io_time_recursive": [],
    "sectors_recursive": []
  }
}

Edit: After @Jon Skeet's comment i realised, he's right about Json simple. In a different json parser you can easilly parse your json, and it will handle it as BigInteger. BigInteger has no limit.

Here's an example:

try{
            String line = "{'read':'2015-05-07T19:30:48.165009273+05:30','network':{'rx_bytes':11124,'rx_packets':116,'rx_errors':0,'rx_dropped':0,'tx_bytes':648,'tx_packets':8,'tx_errors':0,'tx_dropped':0},'cpu_stats':{'cpu_usage':{'total_usage':157158138204,'percpu_usage':[157158138204],'usage_in_kernelmode':49530000000,'usage_in_usermode':58420000000},'system_cpu_usage':258964110000000,'throttling_data':{'periods':0,'throttled_periods':0,'throttled_time':0}},'memory_stats':{'usage':73969664,'max_usage':74600448,'stats':{'active_anon':73928704,'active_file':4096,'cache':86016,'hierarchical_memory_limit':18446744073709552000,'inactive_anon':4096,'inactive_file':32768,'mapped_file':32768,'pgfault':62880,'pgmajfault':0,'pgpgin':34656,'pgpgout':34482,'rss':73883648,'rss_huge':67108864,'total_active_anon':73928704,'total_active_file':4096,'total_cache':86016,'total_inactive_anon':4096,'total_inactive_file':32768,'total_mapped_file':32768,'total_pgfault':62880,'total_pgmajfault':0,'total_pgpgin':34656,'total_pgpgout':34482,'total_rss':73883648,'total_rss_huge':67108864,'total_unevictable':0,'total_writeback':0,'unevictable':0,'writeback':0},'failcnt':0,'limit':2099310592},'blkio_stats':{'io_service_bytes_recursive':[],'io_serviced_recursive':[],'io_queue_recursive':[],'io_service_time_recursive':[],'io_wait_time_recursive':[],'io_merged_recursive':[],'io_time_recursive':[],'sectors_recursive':[]}}";
            line = line.replaceAll( "'", "\"" );
            while( line != null ){

                JsonObject asJsonObject = new JsonParser().parse( line ).getAsJsonObject().get( "network" ).getAsJsonObject();
                Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();

                for( Entry<String, JsonElement> entry : entrySet ){
                    System.out.println( entry.getKey() + " : " + entry.getValue() );
                }
            }
        }
        catch( Exception e ){
            System.out.println( "Error occured :" + e );
        }

I used gson to parse your json. Thanks @Jon Skeet.

Sercan Ozdemir
  • 4,641
  • 3
  • 34
  • 64
  • 2
    There are multiple ways this *could* be handled by a good JSON parser *in Java*, such as using `BigInteger`, `BigDecimal` or `double`. It's not *inherently* an issue in parsing JSON in Java - it's just a limitation of JSON-simple, IMO. – Jon Skeet May 12 '15 at 06:25
0

18446744073709551615 is 2^64 and until Java 8 the maximum value of a long is 2^63 - 1 (which is 9223372036854775807). In Java 8, you can have an unsigned long which is 2^64 but then you're tying yourself to a specific minimum version of Java.

Checking the source of org.json.simple.parser.JSONParser, etc, neither BigInteger nor BigDecimal are mentioned, so it looks like you'll need an alternative parser.

Some JSON parsers give you explicit control over this behaviour, e.g. in Jackson you have

mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
mapper.enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS);

There's some useful information in this question too.

Community
  • 1
  • 1
Steve Chaloner
  • 8,162
  • 1
  • 22
  • 38
  • How do you "use" a `BigInteger` to fix the OP's code? An example would be helpful. – ajb May 12 '15 at 06:25