d语言json的解析
d语言json的解析
轻舞凋零 发表于2年前
d语言json的解析
  • 发表于 2年前
  • 阅读 65
  • 收藏 0
  • 点赞 1
  • 评论 0

移动开发云端新模式探索实践 >>>   

摘要: d语言json的解析

参考自d程序设计语言---我的博客http://my.oschina.net/u/218155/blog?fromerr=SwOkb7Sw fllow me

json库的使用

import std.stdio;
import std.json;


void main() {
	//convert json string to json-value
	string s = "{\"name\":\"tom\",\"age\":12,\"grade\":\"[21,32,56,90]\"}";
	JSONValue strToJV = parseJSON(s);
	writeln(strToJV["name"].str(),strToJV["age"].integer());
	
	//convert json-value to json string
	// JSONValue[string]               object;实际上对应一个JSONValue[string] 的关联数组
 	JSONValue  JVToStr = ["name":"tom"];
	JVToStr.object["age"] = JSONValue(12);
	JVToStr.object["grade"] = JSONValue([21,32,56]);
	JVToStr.object["grade"].array ~= JSONValue(90);
	writeln(JVToStr.toString);
	
}

D语言用JSONValue结构存储json数据

JSONValue通过union Store 存储数据,type_tag存储数据类型

union Store
    {
        string                          str;
        long                            integer;
        ulong                           uinteger;
        double                          floating;
        JSONValue[string]               object;
        JSONValue[]                     array;
    }
    private Store store;
    private JSON_TYPE type_tag;

一堆的值判断。

JSONValue通过tostring方法调用toJSON方法调用

这个函数通过toValue去做判断和处理

string toJSON(in JSONValue* root, in bool pretty = false, in JSONOptions options = JSONOptions.none)
{
    auto json = appender!string();

    void toString(string str)
    {
        json.put('"');

        foreach (dchar c; str)
        {
            switch(c)
            {
                case '"':       json.put("\\\"");       break;
                case '\\':      json.put("\\\\");       break;
                case '/':       json.put("\\/");        break;
                case '\b':      json.put("\\b");        break;
                case '\f':      json.put("\\f");        break;
                case '\n':      json.put("\\n");        break;
                case '\r':      json.put("\\r");        break;
                case '\t':      json.put("\\t");        break;
                default:
                    appendJSONChar(&json, c,
                                   (msg) { throw new JSONException(msg); });
            }
        }

        json.put('"');
    }

    void toValue(in JSONValue* value, ulong indentLevel)
    {
        void putTabs(ulong additionalIndent = 0)
        {
            if(pretty)
                foreach(i; 0 .. indentLevel + additionalIndent)
                    json.put("    ");
        }
        void putEOL()
        {
            if(pretty)
                json.put('\n');
        }
        void putCharAndEOL(char ch)
        {
            json.put(ch);
            putEOL();
        }

        final switch(value.type)
        {
            case JSON_TYPE.OBJECT:
                if(!value.store.object.length)
                {
                    json.put("{}");
                }
                else
                {
                    putCharAndEOL('{');
                    bool first = true;

                    void emit(R)(R names)
                    {
                        foreach (name; names)
                        {
                            auto member = value.store.object[name];
                            if(!first)
                                putCharAndEOL(',');
                            first = false;
                            putTabs(1);
                            toString(name);
                            json.put(':');
                            if(pretty)
                                json.put(' ');
                            toValue(&member, indentLevel + 1);
                        }
                    }

                    import std.algorithm : sort;
                    auto names = value.store.object.keys;
                    sort(names);
                    emit(names);

                    putEOL();
                    putTabs();
                    json.put('}');
                }
                break;

            case JSON_TYPE.ARRAY:
                if(value.store.array.empty)
                {
                    json.put("[]");
                }
                else
                {
                    putCharAndEOL('[');
                    foreach (i, ref el; value.store.array)
                    {
                        if(i)
                            putCharAndEOL(',');
                        putTabs(1);
                        toValue(&el, indentLevel + 1);
                    }
                    putEOL();
                    putTabs();
                    json.put(']');
                }
                break;

            case JSON_TYPE.STRING:
                toString(value.store.str);
                break;

            case JSON_TYPE.INTEGER:
                json.put(to!string(value.store.integer));
                break;

            case JSON_TYPE.UINTEGER:
                json.put(to!string(value.store.uinteger));
                break;

            case JSON_TYPE.FLOAT:
                import std.math : isNaN, isInfinity;

                auto val = value.store.floating;

                if (val.isNaN) {
                    if (options & JSONOptions.specialFloatLiterals) {
                        toString(JSONFloatLiteral.nan);
                    }
                    else {
                        throw new JSONException(
                            "Cannot encode NaN. Consider passing the specialFloatLiterals flag.");
                    }
                }
                else if (val.isInfinity) {
                    if (options & JSONOptions.specialFloatLiterals) {
                        toString((val > 0) ?  JSONFloatLiteral.inf : JSONFloatLiteral.negativeInf);
                    }
                    else {
                        throw new JSONException(
                            "Cannot encode Infinity. Consider passing the specialFloatLiterals flag.");
                    }
                }
                else {
                    json.put(to!string(val));
                }
                break;

            case JSON_TYPE.TRUE:
                json.put("true");
                break;

            case JSON_TYPE.FALSE:
                json.put("false");
                break;

            case JSON_TYPE.NULL:
                json.put("null");
                break;
        }
    }

    toValue(root, 0);
    return json.data;
}






  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 13
博文 99
码字总数 16794
×
轻舞凋零
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: