Permalink
Browse files

Made it possible to drop null placeholders from array output.

This can be used when it's clear that the consumer is able to deal with
this, as web browsers are. Thanks to Yatin Chawathe for the patch.

git-svn-id: https://jsoncpp.svn.sourceforge.net/svnroot/jsoncpp/trunk@249 1f120ed1-78a5-a849-adca-83f0a9e25bb6
  • Loading branch information...
1 parent dc8e373 commit df0ccbd6a61a170e471095ac577d1980241f206f aaronjacobs committed with rjeczalik Mar 12, 2012
Showing with 36 additions and 2 deletions.
  1. +8 −0 include/json/writer.h
  2. +10 −2 src/lib_json/json_writer.cpp
  3. +18 −0 src/test_lib_json/main.cpp
View
@@ -40,6 +40,13 @@ namespace Json {
void enableYAMLCompatibility();
+ /** \brief Drop the "null" string from the writer's output for nullValues.
+ * Strictly speaking, this is not valid JSON. But when the output is being
+ * fed to a browser's Javascript, it makes for smaller output and the
+ * browser can handle the output just fine.
+ */
+ void dropNullPlaceholders();
+
public: // overridden from Writer
virtual std::string write( const Value &root );
@@ -48,6 +55,7 @@ namespace Json {
std::string document_;
bool yamlCompatiblityEnabled_;
+ bool dropNullPlaceholders_;
};
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way.
@@ -192,7 +192,8 @@ Writer::~Writer()
// //////////////////////////////////////////////////////////////////
FastWriter::FastWriter()
- : yamlCompatiblityEnabled_( false )
+ : yamlCompatiblityEnabled_( false ),
+ dropNullPlaceholders_( false )
{
}
@@ -204,6 +205,13 @@ FastWriter::enableYAMLCompatibility()
}
+void
+FastWriter::dropNullPlaceholders()
+{
+ dropNullPlaceholders_ = true;
+}
+
+
std::string
FastWriter::write( const Value &root )
{
@@ -220,7 +228,7 @@ FastWriter::writeValue( const Value &value )
switch ( value.type() )
{
case nullValue:
- document_ += "null";
+ if (!dropNullPlaceholders_) document_ += "null";
break;
case intValue:
document_ += valueToString( value.asLargestInt() );
View
@@ -1399,6 +1399,23 @@ ValueTest::checkIsEqual( const Json::Value &x, const Json::Value &y )
JSONTEST_ASSERT( y.compare( x ) == 0 );
}
+
+struct WriterTest : JsonTest::TestCase
+{
+};
+
+
+JSONTEST_FIXTURE( WriterTest, dropNullPlaceholders )
+{
+ Json::FastWriter writer;
+ Json::Value nullValue;
+ JSONTEST_ASSERT( writer.write(nullValue) == "null\n" );
+
+ writer.dropNullPlaceholders();
+ JSONTEST_ASSERT( writer.write(nullValue) == "\n" );
+}
+
+
int main( int argc, const char *argv[] )
{
JsonTest::Runner runner;
@@ -1420,5 +1437,6 @@ int main( int argc, const char *argv[] )
JSONTEST_REGISTER_FIXTURE( runner, ValueTest, compareArray );
JSONTEST_REGISTER_FIXTURE( runner, ValueTest, compareObject );
JSONTEST_REGISTER_FIXTURE( runner, ValueTest, compareType );
+ JSONTEST_REGISTER_FIXTURE( runner, WriterTest, dropNullPlaceholders );
return runner.runCommandLine( argc, argv );
}

0 comments on commit df0ccbd

Please sign in to comment.