借鉴微软官方示例里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();
}
原文地址:https://www.cnblogs.com/woodytian/p/4837499.html