JSON data processing.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using ProjectC.Models;
namespace ProjectC.Core
{
public class DataProcessor : IDataProcessor
{
private bool IsNumeric(string input)
{
return long.TryParse(input, out _);
}
public bool IsJsonValid(string jsonString)
{
try
{
// ensure that JSON schema is valid
var jsonObject = JsonConvert.DeserializeObject<dynamic>(value: jsonString);
return true;
}
catch
{
return false;
}
}
public List<DataItem> ProcessData(string jsonString)
{
var items = new List<DataItem>();
if (string.IsNullOrEmpty(jsonString))
return items;
var jsonObject = JsonConvert.DeserializeObject<dynamic>(value: jsonString);
foreach (dynamic item in jsonObject)
{
var opA = "";
var opB = "";
var result = "";
var isValid = false;
if (item.a != null)
opA = item.a;
else if (item.aaa != null)
opA = item.aaa;
if (item.b != null)
opB = item.b;
else if (item.bbb != null)
opB = item.bbb;
var itemInfo = new DataItem();
if (IsNumeric(opA) && IsNumeric(opB))
{
var operandA = Convert.ToInt64(opA);
var operandB = Convert.ToInt64(opB);
var aValid = false;
var bValid = false;
if (operandA < int.MinValue)
result = "error";
else if (operandA > int.MaxValue)
result = "error";
else
aValid = true;
if (operandB < int.MinValue)
result = "error";
else if (operandB > int.MaxValue)
result = "error";
else
bValid = true;
if (aValid && bValid)
{
result = (operandA + operandB).ToString();
isValid = true;
}
}
else
{
result = "error";
}
itemInfo.OperandA = opA;
itemInfo.OperandB = opB;
itemInfo.Result = result;
itemInfo.IsValid = isValid;
items.Add(itemInfo);
}
return items;
}
}
}