zoukankan      html  css  js  c++  java
  • 借鉴微软官方示例里Json和String的转换

    在类的定义里加上转换过程

    Json->string

    public User(string jsonString) : this()
    {
        JsonObject jsonObject = JsonObject.Parse(jsonString);
        Id = jsonObject.GetNamedString(idKey, "");
    
        IJsonValue phoneJsonValue = jsonObject.GetNamedValue(phoneKey);
        if (phoneJsonValue.ValueType == JsonValueType.Null)
        {
            Phone = null;
        }
        else
        {
            Phone = phoneJsonValue.GetString();
        }
    
        Name = jsonObject.GetNamedString(nameKey, "");
        Timezone = jsonObject.GetNamedNumber(timezoneKey, 0);
        Verified = jsonObject.GetNamedBoolean(verifiedKey, false);
    
        foreach (IJsonValue jsonValue in jsonObject.GetNamedArray(educationKey, new JsonArray()))
        {
            if (jsonValue.ValueType == JsonValueType.Object)
            {
                Education.Add(new School(jsonValue.GetObject()));
            }
        }
    }
    

    但是会出错,不能生成Json变量,检查发现是string格式问题,需要以大括号开头

    test = test.Replace("200 OK", "");
    

    把开头的状态字段去掉,还是不行,不能正常识别里边字段,应该还是格式问题,是数组形式。
    继续调整 / 换成旧的模式

    string->Json

    public string Stringify()
    {
        JsonArray jsonArray = new JsonArray();
        foreach (School school in Education)
        {
            jsonArray.Add(school.ToJsonObject());
        }
    
        JsonObject jsonObject = new JsonObject();
        jsonObject[idKey] = JsonValue.CreateStringValue(Id);
    
        // Treating a blank string as null
        if (String.IsNullOrEmpty(Phone))
        {
            jsonObject[phoneKey] = JsonValue.CreateNullValue();
        }
        else
        {
            jsonObject[phoneKey] = JsonValue.CreateStringValue(Phone);
        }
    
        jsonObject[nameKey] = JsonValue.CreateStringValue(Name);
        jsonObject[educationKey] = jsonArray;
        jsonObject[timezoneKey] = JsonValue.CreateNumberValue(Timezone);
        jsonObject[verifiedKey] = JsonValue.CreateBooleanValue(Verified);
    
        return jsonObject.Stringify();
    }
    
  • 相关阅读:
    最全的常用正则表达式大全——包括校验数字、字符、一些特殊的需求等等
    xcode6+ios8最新真机调试教程
    新手学习ios开发的辅助工具
    IOS事件传递之hitTest:withEvent
    <转>Singletons in Objective-C
    iOS机身振动提醒
    (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
    对数组进行排序
    字符串去掉空格问题
    NSArray排序方法
  • 原文地址:https://www.cnblogs.com/woodytian/p/4837499.html
Copyright © 2011-2022 走看看