Menu

#20 asString() of intValue throws exception

0.5.0
closed-wont-fix
nobody
None
5
2015-03-06
2010-06-26
sorenriise
No

I had expected just about everything should be able to retrieve as String -- including objects and arrays (feature suggestion).

reader.parse("{\"intvalue\":1}",root);
if (root["intvalue"].isConvertibleTo(Json::stringValue)) // isConvertibleTo is returning true
cout << root["intvalue"].asString() // throws exception......

Discussion

  • Anonymous

    Anonymous - 2010-09-16

    I ran into this bug as well. If "isConvertibleTo" return true, I expected asX() to work, but it does not for int/uint/real.

    Here is a simple patch to fix it:

    diff -r 3f652b479082 jsoncpp/src/lib_json/json_value.cpp
    --- a/jsoncpp/src/lib_json/json_value.cpp Wed Sep 15 11:16:11 2010 -0400
    +++ b/jsoncpp/src/lib_json/json_value.cpp Thu Sep 16 12:08:41 2010 -0400
    @@ -8,7 +8,9 @@
    #ifdef JSON_USE_CPPTL
    # include <cpptl/conststring.h>
    #endif
    +#include <iosfwd>
    +#include <sstream> // size_t
    #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
    # include "json_batchallocator.h"
    #endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
    @@ -716,6 +718,11 @@
    case intValue:
    case uintValue:
    case realValue:
    + {
    + std::ostringstream os;
    + os << ((type_ == intValue) ? value_.int_ : (type_ == uintValue) ? value_.uint_ : value_.real_);
    + return os.str();
    + }
    case arrayValue:
    case objectValue:
    JSON_ASSERT_MESSAGE( false, "Type is not convertible to string" );

     
  • Sergey Kolomenkin

    Following code is not correct:

    > os << ((type_ == intValue) ? value_.int_ : (type_ == uintValue) ?
    value_.uint_ : value_.real_);

    C++ will try to cast the whole expression "((type_ == intValue) ? value_.int_ : (type_ == uintValue) ?
    value_.uint_ : value_.real_)" to one type (double will be used I think).
    So int and uint will be converted to double. Perhaps it may loose data on converting uint to double.
    It is better to use smth. like "if(type_ == intValue) os << value_.int_; else ..."

     
  • Christopher Dunn

    Objects and arrays are serializable to strings, but not strictly convertible. Maybe it's an unfair distinction, but since serialization has so many special cases, we're stuck with this for now.

     
  • Christopher Dunn

    • Description has changed:

    Diff:

    --- old
    +++ new
    @@ -1,4 +1,3 @@
    -
     I had expected just about everything should be able to retrieve as String -- including objects and arrays \(feature suggestion\).
    
     reader.parse\("\{\"intvalue\":1\}",root\);
    
    • status: open --> closed-wont-fix
    • Group: --> 0.5.0
     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.