LitJson使用(二)

  工作需要将JSON格式数据,转换成Schema格式数据。

  如JSON数据:

{
  "a1":"a11111",
  "b1":32,
  "c1":[1,"ttt"],
  "d1":{
          "ddd1":"mmmm"
       }
}

  转换成Schema格式后:

{
  "type": "object",
  "exampleValue": {},
  "description": "",
  "title": "",
  "properties": {
    "a1": {
      "type": "string",
      "exampleValue": "a11111",
      "description": ""
    },
    "b1": {
      "type": "number",
      "exampleValue": 32,
      "description": "",
      "format": ""
    },
    "c1": {
      "type": "array",
      "exampleValue": [],
      "description": "",
      "properties": [
        {
          "type": "number",
          "exampleValue": 1,
          "description": "",
          "format": ""
        },
        {
          "type": "string",
          "exampleValue": "ttt",
          "description": ""
        }
      ]
    },
    "d1": {
      "type": "object",
      "exampleValue": {},
      "description": "",
      "title": "",
      "properties": {
        "ddd1": {
          "type": "string",
          "exampleValue": "mmmm",
          "description": ""
        }
      }
    }
  }
}

  注意看属性:exampleValue,当数据类型是数组(array)时,以[]标识,当数据类型是对象(object)时,以{}标识

  如果赋值:

JsonData jd = new JsonData();
jd["type"] = "object";
jd["exampleValue"] = new JsonData();  // 此处未指名类型
jd["title"] = "";

string str = JsonMapper.ToJson(jd); // 对象转转换成字符串

  这样处理的结果是,str为:  {"type":"object", "exampleValue": ,"title":""}   // 出来结果不是标准的JSON格式,按JSON使用时会报错。

 

  处理办法:指定数据类型(参考:https://blog.csdn.net/DoyoFish/article/details/90543859)

  代码如下:

JsonData jd = new JsonData();
jd["type"] = "object";
jd["exampleValue"] = new JsonData();  // 此处未指名类型

jd["exampleValue"].SetJsonType(JsonType.Object);  // 指定类型为对象:object
// jd["exampleValue"].SetJsonType(JsonType.Array);  // 指定类型为数组:array
jd["title"] = "";

  这样,转换成字符串后结果如下:

  对象(object)时,str为:  {"type":"object", "exampleValue":{} ,"title":""}

  数组(array)时,str为:  {"type":"object", "exampleValue":[] ,"title":""}

  这样处理后就达到了要求。

 

  另,处理转换为字符串时,中文被编码处理,不能直接显示为中文,而是: \uxxxx或\Uxxxx样式。

  参考地址:https://blog.csdn.net/qq_39484391/article/details/80982810中的方法二

  处理方式:

string ss1 = sData.ToJson();
Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
String ss2 = reg.Replace(sData.ToJson(), delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });

  这样处理后,中文就可正常显示了。

 

  

  

 

posted @ 2021-10-29 11:42  Tiger.liang  阅读(327)  评论(0编辑  收藏  举报