Commit da7c2c0ee90104524ed98a2370af0ea70a0f6d0d
1 parent
d2260925
Fix json serialization for {x | -1 < x < 1} (fixes #308)
JSON serialization was preserving the value as presented, but JSON doesn't accept decimal values without a 0 before the decimal point.
Showing
3 changed files
with
34 additions
and
2 deletions
ChangeLog
libqpdf/QPDF_Real.cc
| ... | ... | @@ -25,7 +25,30 @@ QPDF_Real::unparse() |
| 25 | 25 | JSON |
| 26 | 26 | QPDF_Real::getJSON() |
| 27 | 27 | { |
| 28 | - return JSON::makeNumber(this->val); | |
| 28 | + // While PDF allows .x or -.x, JSON does not. Rather than | |
| 29 | + // convering from string to double and back, just handle this as a | |
| 30 | + // special case for JSON. | |
| 31 | + std::string result; | |
| 32 | + if (this->val.length() == 0) | |
| 33 | + { | |
| 34 | + // Can't really happen... | |
| 35 | + result = "0"; | |
| 36 | + } | |
| 37 | + else if (this->val.at(0) == '.') | |
| 38 | + { | |
| 39 | + result = "0" + this->val; | |
| 40 | + } | |
| 41 | + else if ((this->val.length() >= 2) && | |
| 42 | + (this->val.at(0) == '-') && | |
| 43 | + (this->val.at(1) == '.')) | |
| 44 | + { | |
| 45 | + result = "-0." + this->val.substr(2); | |
| 46 | + } | |
| 47 | + else | |
| 48 | + { | |
| 49 | + result = this->val; | |
| 50 | + } | |
| 51 | + return JSON::makeNumber(result); | |
| 29 | 52 | } |
| 30 | 53 | |
| 31 | 54 | QPDFObject::object_type_e | ... | ... |
libtests/json.cc
| ... | ... | @@ -3,7 +3,7 @@ |
| 3 | 3 | #include <iostream> |
| 4 | 4 | #include <assert.h> |
| 5 | 5 | |
| 6 | -static void check(JSON& j, std::string const& exp) | |
| 6 | +static void check(JSON const& j, std::string const& exp) | |
| 7 | 7 | { |
| 8 | 8 | if (exp != j.unparse()) |
| 9 | 9 | { |
| ... | ... | @@ -69,6 +69,10 @@ static void test_main() |
| 69 | 69 | " ],\n" |
| 70 | 70 | " \"yes\": false\n" |
| 71 | 71 | "}"); |
| 72 | + check(QPDFObjectHandle::newReal("0.12").getJSON(), "0.12"); | |
| 73 | + check(QPDFObjectHandle::newReal(".34").getJSON(), "0.34"); | |
| 74 | + check(QPDFObjectHandle::newReal("-0.56").getJSON(), "-0.56"); | |
| 75 | + check(QPDFObjectHandle::newReal("-.78").getJSON(), "-0.78"); | |
| 72 | 76 | } |
| 73 | 77 | |
| 74 | 78 | static void check_schema(JSON& obj, JSON& schema, bool exp, | ... | ... |