Browse Source

Add autoFormattingIndent property

Girish Ramakrishnan 9 years ago
parent
commit
1ae6f842df
2 changed files with 20 additions and 7 deletions
  1. 16 7
      src/json.cpp
  2. 4 0
      src/json.h

+ 16 - 7
src/json.cpp

@@ -51,7 +51,7 @@ QString JsonReader::errorString() const
 }
 
 JsonWriter::JsonWriter()
-    : m_autoFormatting(false)
+    : m_autoFormatting(false), m_autoFormattingIndent(4, QLatin1Char(' '))
 {
 }
 
@@ -69,6 +69,17 @@ bool JsonWriter::autoFormatting() const
     return m_autoFormatting;
 }
 
+
+void JsonWriter::setAutoFormattingIndent(int spacesOrTabs)
+{
+    m_autoFormattingIndent = QString(qAbs(spacesOrTabs), QLatin1Char(spacesOrTabs >= 0 ? ' ' : '\t'));
+}
+
+int JsonWriter::autoFormattingIndent() const
+{
+    return m_autoFormattingIndent.count(QLatin1Char(' ')) - m_autoFormattingIndent.count(QLatin1Char('\t'));
+}
+
 static QString escape(const QVariant &variant)
 {
     QString str = variant.toString();
@@ -112,21 +123,20 @@ QString JsonWriter::stringify(const QVariant &variant, int depth)
                 if (m_autoFormatting)
                     result += QLatin1Char(' ');
             }
-            result += stringify(list[i]);
+            result += stringify(list[i], depth+1);
         }
         result += QLatin1Char(']');
     } else if (variant.type() == QVariant::Map) {
-        QString indent(depth, QLatin1Char(' '));
+        QString indent = m_autoFormattingIndent.repeated(depth);
         QVariantMap map = variant.toMap();
-        QVariantMap::const_iterator it = map.constBegin();
-        if (m_autoFormatting) {
+        if (m_autoFormatting && depth != 0) {
             result += QLatin1Char('\n');
             result += indent;
             result += QLatin1String("{\n");
         } else {
             result += QLatin1Char('{');
         }
-        while (it != map.constEnd()) {
+        for (QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it) {
             if (it != map.constBegin()) {
                 result += QLatin1Char(',');
                 if (m_autoFormatting)
@@ -136,7 +146,6 @@ QString JsonWriter::stringify(const QVariant &variant, int depth)
                 result += indent + QLatin1Char(' ');
             result += QLatin1Char('\"') + escape(it.key()) + QLatin1String("\":");
             result += stringify(it.value(), depth+1);
-            ++it;
         }
         if (m_autoFormatting) {
             result += QLatin1Char('\n');

+ 4 - 0
src/json.h

@@ -43,9 +43,13 @@ public:
     void setAutoFormatting(bool autoFormat);
     bool autoFormatting() const;
 
+    void setAutoFormattingIndent(int spaceOrTabs);
+    int autoFormattingIndent() const;
+
 private:
     QString stringify(const QVariant &variant, int depth = 0);
     bool m_autoFormatting;
+    QString m_autoFormattingIndent;
 };
 
 #endif // JSON_H