private static DataTable JArrayToDataTable(JArray jarr) { if (jarr.Count > 0) { //StringBuilder columns = new StringBuilder(); DataTable table = new DataTable(); JObject objcolumns = jarr[0] as JObject; foreach (JToken jkon in objcolumns.AsJEnumerable()) { string name = ((JProperty)jkon).Name; //columns.Append(name + ","); table.Columns.Add(name); } for (int i = 0; i < jarr.Count; i++) { DataRow row = table.NewRow(); JObject obj = jarr[i] as JObject; foreach (JToken jkon in obj.AsJEnumerable()) { string name = ((JProperty)jkon).Name; string value = ((JProperty)jkon).Value.ToString(); row[name] = value; } table.Rows.Add(row); } return(table); } else { return(new DataTable()); } }
private void DiffAsObject(JObject expected, JObject actual, JObject result) { if (actual == null) { result.Add(expected.Path, GetDiff(expected, actual)); } else { var expectedMap = new JsonNodeMap(expected, Config); var actualMap = new JsonNodeMap(actual, Config); foreach (var expectedToken in expected.AsJEnumerable()) { var actualValue = actualMap[expectedToken]; var expectedValue = expectedMap[expectedToken]; DiffTokens(expectedValue, actualValue, result); } foreach (var unexpectedToken in actual.AsJEnumerable().Where(a => expectedMap[a] == null)) { var diff = unexpectedToken is JProperty ? ((JProperty)unexpectedToken).Value : unexpectedToken; result.Add(unexpectedToken.Path, GetDiff(null, diff)); } } }
public static DataTable JsonToDataTable(string json) { DataTable table = new DataTable(); //JsonStr为Json字符串 JArray array = JsonConvert.DeserializeObject(json) as JArray;//反序列化为数组 if (array.Count > 0) { StringBuilder columns = new StringBuilder(); JObject objColumns = array[0] as JObject; //构造表头 foreach (JToken jkon in objColumns.AsJEnumerable <JToken>()) { string name = ((JProperty)(jkon)).Name; columns.Append(name + ","); table.Columns.Add(name); } //向表中添加数据 for (int i = 0; i < array.Count; i++) { DataRow row = table.NewRow(); JObject obj = array[i] as JObject; foreach (JToken jkon in obj.AsJEnumerable <JToken>()) { string name = ((JProperty)(jkon)).Name; string value = ((JProperty)(jkon)).Value.ToString(); row[name] = value; } table.Rows.Add(row); } } return(table); }
static void TestJson() { DicomStation station = new DicomStation(StationCategories.Server) { AE = "a", IPAddress = null, }; //string output = JsonConvert.SerializeObject(station); //Console.WriteLine(output); JsonSerializer serializer = new JsonSerializer(); using (StreamWriter fs = new StreamWriter(@"D:\dias.json")) { using (JsonWriter writer = new JsonTextWriter(fs)) { serializer.Serialize(writer, station); } } using (StreamReader sr = File.OpenText(@"C:\Users\fmisx\Desktop\AadProvider.Configuration.json")) { JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(sr)); Parallel.ForEach(o.AsJEnumerable(), item => { Console.WriteLine($"{item}"); }); } }
public void NullJObjectAsJEnumerableReturnsNull() { JObject o = null; var enumerable = o.AsJEnumerable(); Assert.IsNull(enumerable); }
public int GetHashCode(JToken obj) { switch (obj.Type) { case JTokenType.Null: case JTokenType.Undefined: case JTokenType.None: return(0); case JTokenType.Bytes: return(Hash.GetCombinedHashCodeForValCollection(obj.Value <byte[]>())); case JTokenType.Array: return(Hash.GetCombinedHashCodeForCollection(obj)); case JTokenType.Object: { JObject j = (JObject)obj; return(Hash.GetCombinedHashCodeForValCollection(j.AsJEnumerable().Select(GetHashCode))); } case JTokenType.Integer: case JTokenType.Float: case JTokenType.Boolean: case JTokenType.Date: { var j = ((JValue)obj); if (j.Value == null) { return(0); } return(j.Value.GetHashCode()); } case JTokenType.String: { { var j = ((JValue)obj); if (j.Value == null) { return(0); } return(StringComparer.InvariantCultureIgnoreCase.GetHashCode(j.Value <string>())); } } } return(obj.GetHashCode()); }
private bool CompareAsObject(JObject expected, JObject actual) { if (actual == null) { return(false); } return (expected.AsJEnumerable() .All(expectedToken => CompareTokens( templateMap[expectedToken], requestMap[expectedToken])) && actual.AsJEnumerable() .All(actualToken => templateMap[actualToken] != null)); }
public void JObjectAsJEnumerableSucceeds() { var o = new JObject( new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)), new JProperty("Test2", "Test2Value"), new JProperty("Test3", null) ); var enumerable = o.AsJEnumerable(); Assert.IsNotNull(enumerable); Assert.AreEqual(o, enumerable); var d = enumerable["Test1"].Value <DateTime>(); Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), d); }
private bool CompareAsObject(JObject expected, JObject actual) { var expectedMap = new JsonNodeMap(expected, Config); var actualMap = new JsonNodeMap(actual, Config); if (actual == null) { return(false); } return (expected.AsJEnumerable() .All(expectedToken => CompareTokens( expectedMap[expectedToken], actualMap[expectedToken])) && actual.AsJEnumerable() .All(actualToken => actualMap[actualToken] != null)); }
private string ValidateBodyAsObject(string actual, JObject expected) { JObject actualJson; try { actualJson = JObject.Parse(actual); } catch (Newtonsoft.Json.JsonReaderException) { return("Body is not parsable to object"); } return(expected.AsJEnumerable().Select(token => { var actualToken = actualJson.GetValue(token.Path, configuration.BodyKeyStringComparison.GetValueOrDefault()); var expectedValue = expected.GetValue(token.Path); return ValidateTokens(actualToken, expectedValue); }).FirstOrDefault(r => r != null)); }
private void DiffAsObject(JObject expected, JObject actual, JObject result) { if (actual == null) { result.Add(expected.Path, GetDiff(expected, actual)); } else { foreach (var expectedToken in expected.AsJEnumerable()) { var actualValue = requestMap[expectedToken]; var expectedValue = templateMap[expectedToken]; DiffTokens(expectedValue, actualValue, result); } foreach (var unexpectedToken in actual.AsJEnumerable().Where(a => templateMap[a] == null)) { var diff = unexpectedToken is JProperty ? ((JProperty)unexpectedToken).Value : unexpectedToken; result.Add(unexpectedToken.Path, GetDiff(null, diff)); } } }
public void AsJEnumerable() { JObject o = null; IJEnumerable <JToken> enumerable = null; enumerable = o.AsJEnumerable(); Assert.IsNull(enumerable); o = new JObject( new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)), new JProperty("Test2", "Test2Value"), new JProperty("Test3", null) ); enumerable = o.AsJEnumerable(); Assert.IsNotNull(enumerable); Assert.AreEqual(o, enumerable); DateTime d = enumerable["Test1"].Value <DateTime>(); Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), d); }
public void AsJEnumerable() { JObject o = null; IJEnumerable<JToken> enumerable = null; enumerable = o.AsJEnumerable(); Assert.IsNull(enumerable); o = new JObject( new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)), new JProperty("Test2", "Test2Value"), new JProperty("Test3", null) ); enumerable = o.AsJEnumerable(); Assert.IsNotNull(enumerable); Assert.AreEqual(o, enumerable); DateTime d = enumerable["Test1"].Value<DateTime>(); Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), d); }
public IActionResult Export(string jsontree, string exclename) { try { if (string.IsNullOrEmpty(exclename)) { return(Ok("exclename不能为空!")); } var tempName = "temp"; var rootPath = @"F://Temp"; //var rootPath = @"http://192.168.0.105:8080//app"; if (System.IO.Directory.Exists(rootPath) == false) { System.IO.Directory.CreateDirectory(rootPath); } var newFile = rootPath + "//" + tempName + ".xls"; if (System.IO.File.Exists(newFile)) { System.IO.File.Delete(newFile); } var client = new RestClient(Configuration["ConnectionStrings:JavaServerPath"].ToString()); // client.Authenticator = new HttpBasicAuthenticator(username, password); var request = new RestRequest("getAnalysisData", Method.POST); request.AddParameter("Content-Type", "multipart/form-data; boundary=<calculated when request is sent>"); //string jsonstr = "{\"id\":5,\"parentid\":4,\"menuename\":\"拆除未尽区\",\"type\":\"polygon\",\"createtime\":\"2020-06-17 00:00:00\",\"subAnalysisMenue\":[],\"tablename\":\"ccwjq\"}"; // string jsonstr = "{\"id\":2,\"parentid\":1,\"menuename\":\"权属分析\",\"type\":\"polygon\",\"createtime\":\"2020-06-17 00:00:00\",\"subAnalysisMenue\":[],\"tablename\":\"dltb\"}"; request.AddParameter("jsonTree", jsontree); // adds to POST or URL querystring based on Method // request.AddParameter("jsonTree", jsonstr); // execute the request IRestResponse response = client.Execute(request); JObject jobj = (JObject)JsonConvert.DeserializeObject(response.Content); //JsonStr为Json字符串 JArray array = JsonConvert.DeserializeObject(jobj["result"].ToString()) as JArray;//反序列化为数组 if (array.Count > 0) { using (var fs = new FileStream(newFile, FileMode.Create, FileAccess.Write)) { IWorkbook workbook = new XSSFWorkbook(); var sheet = workbook.CreateSheet("Data"); var header = sheet.CreateRow(0); JObject objColumns = array[0] as JObject; int headerCount = 0; //构造表头 foreach (JToken jkon in objColumns.AsJEnumerable <JToken>()) { string name = ((JProperty)(jkon)).Name.ToUpper(); if (name == "AREA" || name == "OBJECTID" || name == "SHAPE") { continue; } KeyValueHelper.matchKey = ":"; KeyValueHelper.matchValue = ","; Dictionary <object, object> conents = KeyValueHelper.GetConentByString(KeyValueHelper.data); if (conents.ContainsKey(name)) { name = conents[name.ToUpper()].ToString(); } header.CreateCell(headerCount).SetCellValue(name); headerCount++; } //向表中添加数据 for (int i = 0; i < array.Count; i++) { var datarow = sheet.CreateRow(i + 1); JObject obj = array[i] as JObject; int cellCount = 0; foreach (JToken jkon in obj.AsJEnumerable <JToken>()) { string Name = ((JProperty)(jkon)).Name.ToString().ToUpper(); if (Name == "AREA" || Name == "OBJECTID" || Name == "SHAPE") { continue; } string value = ((JProperty)(jkon)).Value.ToString(); datarow.CreateCell(cellCount).SetCellValue(value); cellCount++; } } workbook.Write(fs); } } else { return(BadRequest()); } var memory = new MemoryStream(); using (var stream = new FileStream(newFile, FileMode.Open)) { stream.CopyTo(memory); } memory.Position = 0; if (System.IO.File.Exists(newFile)) { System.IO.File.Delete(newFile); } if (System.IO.Directory.Exists(rootPath) == true) { System.IO.Directory.Delete(rootPath); } return(File(memory, "application/vnd.ms-excel", exclename + "11.xlsx")); } catch (Exception ex) { return(Ok(ex.Message.ToString())); } }
public async Task <JsonResult> InvoiceListExportToExcel([FromBody] dynamic Lista) { JObject dp = (JObject)Lista[0].ColunasEXCEL; string sWebRootFolder = _generalConfig.FileUploadFolder + "Clientes\\" + "tmp\\"; string user = User.Identity.Name; user = user.Replace("@", "_"); user = user.Replace(".", "_"); string sFileName = @"" + user + "_ExportEXCEL.xlsx"; string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName); FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); var memory = new MemoryStream(); using (var fs = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Create, FileAccess.Write)) { IWorkbook workbook; workbook = new XSSFWorkbook(); ISheet excelSheet; excelSheet = workbook.CreateSheet("Faturas Notas de Crédito"); IRow row = excelSheet.CreateRow(0); var columns = dp.AsJEnumerable().ToList(); for (int i = 0; i < columns.Count; i++) { var column = columns[i]; var isHidden = true; var label = ""; try { isHidden = (bool)column.First()["hidden"]; label = (string)column.First()["label"]; } catch { } if (!isHidden) { row.CreateCell(i).SetCellValue(label); } } if (dp != null) { int count = 1; try { foreach (var item in Lista) { row = excelSheet.CreateRow(count); for (int i = 0; i < columns.Count; i++) { var column = columns[i]; var isHidden = true; try { isHidden = (bool)column.First()["hidden"]; } catch { } if (!isHidden) { var _columnPath = column.Path.ToString().Split("."); var columnPath = _columnPath[_columnPath.Length - 1].ToString() /*.ToUpper() + String.Join("", columnPath.Skip(1))*/; object value = null; try { value = item[columnPath]; } catch { } if (value == null) { try { value = item[columnPath.ToUpper()]; } catch { } } if ((new[] { "amountIncludingVAT", "valorPendente" }).Contains(columnPath)) { row.CreateCell(i).SetCellValue((double)(value != null ? decimal.Parse(value.ToString()) : 0)); } else { row.CreateCell(i).SetCellValue(value?.ToString()); } } } count++; } } catch (Exception e) { throw; } } workbook.Write(fs); } using (var stream = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open)) { await stream.CopyToAsync(memory); } memory.Position = 0; return(Json(sFileName)); }