Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize JSON objects

I'm trying to use the get request by:

  req = Net::HTTP::Get.new("/api/v1/users/external/1/features/DOWNLOAD7ab8d82b40/alloc?paymentPlanId=PRO_SUBSCRD725FCCCC6");
  req.add_field('ISV_API_KEY', '548f3d4b34ffdb2f294a870a9728af6940a75b66ba944d8ab6eef5a7543ca3db'); 
  req.add_field('ISV_API_SECRET', '69dafa8923f2b0da8153e6bcca3841de0fa88f1a031a5eb1946e54eb982cef48');                           

  res = Net::HTTP.start("localhost", 3000) {|http|
      res = http.request(req)
  }

'postman` is an application that shows me the result of this request

According to the postman, this request returns me:

{
"total":"1200.0",
"used":"35.0",
"available":1165.0
}

How can I deserialize this Json object? Assuming I want the "used" parameter.

I tried:

json_string = req2.to_json
puts json_string

but I got:

{"accept":["*/*"],"user-agent":["Ruby"],"isv_api_key":["548f3d4b34ffdb2f294a870a9728af6940a75b66ba944d8ab6eef5a7543ca3db"],"isv_api_secret":["69dafa8923f2b0da8153e6bcca3841de0fa88f1a031a5eb1946e54eb982cef48"]}

I also tried:

puts JSON.parse(res)

but I got:

can't convert Net::HTTPOK into String
like image 748
Alon Shmiel Avatar asked Jan 27 '13 09:01

Alon Shmiel


People also ask

What does it mean to deserialize JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). Regards, Daniel.

What is JSON deserialization in C#?

Deserialization. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.

How do you deserialize a JSON object in Python?

The default method of deserialization is json. loads() which takes a string as an input and outputs a JSON dictionary object. To convert the dictionary object to a custom class object, you need to write a deserialize method. The easiest way is to add a static method to the class itself.

What is the difference between serialize and deserialize?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


1 Answers

Use Ruby's JSON library.

res = '{"total":"1200.0","used":"35.0","available":1165.0}'
JSON.parse(res) # => {"total"=>"1200.0", "used"=>"35.0", "available"=>1165.0}

Note: If you're on Ruby 1.8.X you may have to require the json class. Rails requires it for you if you are working within a rails app.

like image 86
Douglas F Shearer Avatar answered Oct 23 '22 12:10

Douglas F Shearer