使用Newtonsoft.Json库实现解析上传的Json格式文件的数据
以以下的Json文件格式为例
{
"Dictionary": [
{
"DictionaryKey": "学历",
"DictionaryValue": "学历",
"ParentKey": "",
"IsKey": 1
},
{
"DictionaryKey": "本科",
"DictionaryValue": "本科",
"ParentKey": "学历",
"IsKey": 0
},
{
"DictionaryKey": "大专",
"DictionaryValue": "大专",
"ParentKey": "学历",
"IsKey": 0
},
{
"DictionaryKey": "硕士",
"DictionaryValue": "硕士",
"ParentKey": "学历",
"IsKey": 0
},
{
"DictionaryKey": "博士",
"DictionaryValue": "博士",
"ParentKey": "学历",
"IsKey": 0
},
{
"DictionaryKey": "设备类型",
"DictionaryValue": "设备类型",
"ParentKey": "",
"IsKey": 1
},
{
"DictionaryKey": "大型",
"DictionaryValue": "大型",
"ParentKey": "设备类型",
"IsKey": 0
},
{
"DictionaryKey": "工作地点",
"DictionaryValue": "工作地点",
"ParentKey": "",
"IsKey": 1
},
{
"DictionaryKey": "常州软件园",
"DictionaryValue": "常州软件园",
"ParentKey": "工作地点",
"IsKey": 0
},
{
"DictionaryKey": "设备大类",
"DictionaryValue": "设备大类",
"ParentKey": "",
"IsKey": 1
},
{
"DictionaryKey": "大新机械",
"DictionaryValue": "大新机械",
"ParentKey": "设备大类",
"IsKey": 0
}
],
"ApplicationInfo": {
"ApplicationFlag": "EQSystem",
"ApplicationName": "设备管理",
"ApplicationType": "Web",
"DataBaseConnectString": "",
"IsEnable": 1,
"ApplicationDescribe": "rrr"
}
}
实体类
public class DictionaryImport
{
///
/// 字典Key
///
public string DictionaryKey { get; set; }
///
/// 字典Value
///
public string DictionaryValue { get; set; }
///
/// 所属字典Key
///
public string ParentKey { get; set; }
///
/// 是否Key 0:否 1:是
///
public int IsKey { get; set; }
}
}
public class ApplicationInfo
{
///
/// 应用标识
///
public string ApplicationFlag { get; set; }
///
/// 应用名称
///
public string ApplicationName { get; set; }
///
/// 应用类别 App、Web
///
public string ApplicationType { get; set; }
///
/// 应用数据库连接
///
public string DataBaseConnectString { get; set; }
///
/// 是否可用 0:否 1:是
///
public int IsEnable { get; set; }
///
/// 应用描述
///
public string ApplicationDescribe { get; set; }
}
json文件解析代码实现
IFormFileCollection formFiles = Request.Form.Files;//上传的文件
foreach (IFormFile file in formFiles)
{
var stream = file.OpenReadStream();
System.IO.StreamReader streamReader = new System.IO.StreamReader(stream);
JsonTextReader jsonTextReader = new JsonTextReader(streamReader);
JObject jsonObject = (JObject)JToken.ReadFrom(jsonTextReader);
//JToken token = jsonObject["Dictionary"];
//foreach (JObject e in token)
//{
// DictionaryImport dictionaryImport = e.ToObject();
//}
string strDictionaryJson = jsonObject["Dictionary"].ToString();//json字符串
string strApplicationJson= jsonObject["ApplicationInfo"].ToString();
//所属应用数据解析
var applicationInfoImport = JsonConvert.DeserializeObject(strApplicationJson);
//字典值数据解析
List dictionaryImports = JsonConvert.DeserializeObject>(strDictionaryJson);
}