Вопрос

Разобрать JSON

Подскажите по работе с JSON

В БП получаю массив данных:

{
    "status": "ok",
    "error_description": "",
    "error": {},
    "data_type": "",
    "total_records": 12,
    "data": [
        {
            "id": 12,
            "uid": "a8d89141-566b-07b1-6614-daf82425ae74",
            "version": 379842381,
            "state": 0,
            "modify_date": "2020-05-03T13:50:22.690",
            "modify_user": "jsokol",
            "create_date": "2020-04-08T10:36:44.609",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "CONVERTATION",
            "event_code": "CONVERTATION",
            "cycle_code": "OPERATION",
            "algorithm": "GENERAL",
            "fixed_amount": 1.08000000,
            "percentage": 1.00000000,
            "minimum_amount": 4.08000000,
            "maximum_amount": 5.08000000,
            "fee_currency": "EUR",
            "country_group": "EU",
            "payment_currency": "",
            "gl": 60245000,
            "account": "",
            "activation_date": "2020-04-08",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "Currency Exchange Operation",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 20,
            "uid": "fcfc544b-6d86-8a8c-6714-beeb80d72b61",
            "version": 425526629,
            "state": 0,
            "modify_date": "2020-05-10T13:58:57.361",
            "modify_user": "azukovs",
            "create_date": "2020-04-23T21:31:48.324",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "OUTWARD",
            "event_code": "OUTWARD",
            "cycle_code": "OPERATION",
            "algorithm": "GENERAL",
            "fixed_amount": 1.33000000,
            "percentage": 19.00000000,
            "minimum_amount": 1.00000000,
            "maximum_amount": 2.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60225000,
            "account": "",
            "activation_date": "2020-04-23",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "STANDART",
            "client_statuses": "",
            "fee_code_description": "Outward Payments",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 21,
            "uid": "fcfc544b-6d86-8a8c-6714-c9eb60ba3868",
            "version": 414943660,
            "state": 0,
            "modify_date": "2020-05-04T17:21:52.021",
            "modify_user": "azukovs",
            "create_date": "2020-04-23T21:35:45.119",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "151000",
            "event_code": "ACCOUNT_OPEN_NEW",
            "cycle_code": "OPERATION",
            "algorithm": "GENERAL",
            "fixed_amount": 1.05000000,
            "percentage": 0.00000000,
            "minimum_amount": 0.00000000,
            "maximum_amount": 0.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60265000,
            "account": "",
            "activation_date": "2020-04-23",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "Open e-Cash Account",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 22,
            "uid": "fcfc544b-6d86-8a8c-6714-cfebd0d18e1b",
            "version": 414944059,
            "state": 0,
            "modify_date": "2020-05-04T17:22:09.987",
            "modify_user": "azukovs",
            "create_date": "2020-04-23T21:37:47.539",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "152000",
            "event_code": "ACCOUNT_CLOSE",
            "cycle_code": "OPERATION",
            "algorithm": "GENERAL",
            "fixed_amount": 1.06000000,
            "percentage": 0.00000000,
            "minimum_amount": 0.00000000,
            "maximum_amount": 0.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60265000,
            "account": "",
            "activation_date": "2020-04-23",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "Close e-Cash Account",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 24,
            "uid": "fcfc544b-6d86-8a8c-6714-d7ebb4d659aa",
            "version": 379028868,
            "state": 0,
            "modify_date": "2020-04-23T21:40:51.325",
            "modify_user": "jsokol",
            "create_date": "2020-04-23T21:40:51.323",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "154000",
            "event_code": "FEE_MANUAL",
            "cycle_code": "MONTH",
            "algorithm": "GENERAL",
            "fixed_amount": 1.24000000,
            "percentage": 0.00000000,
            "minimum_amount": 0.00000000,
            "maximum_amount": 0.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60215000,
            "account": "",
            "activation_date": "2020-04-23",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "e-Wallet management service",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 25,
            "uid": "fcfc544b-6d86-8a8c-6714-daebc479837a",
            "version": 379029080,
            "state": 0,
            "modify_date": "2020-04-23T21:41:51.735",
            "modify_user": "jsokol",
            "create_date": "2020-04-23T21:41:51.732",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "155000",
            "event_code": "FEE_MANUAL",
            "cycle_code": "MONTH",
            "algorithm": "GENERAL",
            "fixed_amount": 1.03000000,
            "percentage": 0.00000000,
            "minimum_amount": 0.00000000,
            "maximum_amount": 0.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60215000,
            "account": "",
            "activation_date": "2020-04-23",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "Inactive e-Wallet management",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 26,
            "uid": "fcfc544b-6d86-8a8c-6714-e1ebb0fbe1e2",
            "version": 379029661,
            "state": 0,
            "modify_date": "2020-04-23T21:44:30.810",
            "modify_user": "jsokol",
            "create_date": "2020-04-23T21:44:30.808",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "171000",
            "event_code": "FEE_MANUAL",
            "cycle_code": "DAY",
            "algorithm": "GENERAL",
            "fixed_amount": 1.21000000,
            "percentage": 0.00000000,
            "minimum_amount": 0.00000000,
            "maximum_amount": 0.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60265000,
            "account": "",
            "activation_date": "2020-04-23",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "SMS Service Maintenance",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 29,
            "uid": "fcfc544b-6d86-8a8c-6714-eceb705bf7e8",
            "version": 379030515,
            "state": 0,
            "modify_date": "2020-04-23T21:48:27.546",
            "modify_user": "jsokol",
            "create_date": "2020-04-23T21:48:27.544",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "173000",
            "event_code": "FEE_MANUAL",
            "cycle_code": "DAY",
            "algorithm": "GENERAL",
            "fixed_amount": 1.23000000,
            "percentage": 0.00000000,
            "minimum_amount": 0.00000000,
            "maximum_amount": 0.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60265000,
            "account": "",
            "activation_date": "2020-04-23",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "Email Service Maintenance",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 36,
            "uid": "dfe34e1e-e3e0-e49b-6814-f1833c2ad799",
            "version": 379842549,
            "state": 0,
            "modify_date": "2020-05-03T13:57:17.132",
            "modify_user": "jsokol",
            "create_date": "2020-05-03T13:57:17.131",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "INWARD",
            "event_code": "INWARD",
            "cycle_code": "OPERATION",
            "algorithm": "GENERAL",
            "fixed_amount": 1.43000000,
            "percentage": 49.00000000,
            "minimum_amount": 1.00000000,
            "maximum_amount": 2.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60225000,
            "account": "",
            "activation_date": "2020-05-03",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "Inward Payments",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 37,
            "uid": "b1a95e84-8225-eb8b-6814-f783b030f703",
            "version": 379842611,
            "state": 0,
            "modify_date": "2020-05-03T13:59:13.399",
            "modify_user": "jsokol",
            "create_date": "2020-05-03T13:59:13.397",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "OUTWARD",
            "event_code": "OUTWARD",
            "cycle_code": "OPERATION",
            "algorithm": "GENERAL",
            "fixed_amount": 3.33000000,
            "percentage": 1.00000000,
            "minimum_amount": 3.33000000,
            "maximum_amount": 3.33000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60225000,
            "account": "",
            "activation_date": "2020-05-03",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "URGENT",
            "client_statuses": "",
            "fee_code_description": "Outward Payments",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 38,
            "uid": "b1a95e84-8225-eb8b-6814-fa83a8bd038d",
            "version": 429115257,
            "state": 0,
            "modify_date": "2020-05-12T15:15:28.410",
            "modify_user": "azukovs",
            "create_date": "2020-05-03T14:00:29.336",
            "create_user": "jsokol",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "INTERNAL",
            "event_code": "INTERNAL",
            "cycle_code": "OPERATION",
            "algorithm": "GENERAL",
            "fixed_amount": 1.09000000,
            "percentage": 0.50000000,
            "minimum_amount": 0.03000000,
            "maximum_amount": 0.05000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60225000,
            "account": "",
            "activation_date": "2020-05-03",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "Internal Payments",
            "fee_dates_status": "ACTIVE"
        },
        {
            "id": 39,
            "uid": "94a5eff9-f8e1-21a3-6814-4095942b65c0",
            "version": 379898769,
            "state": 0,
            "modify_date": "2020-05-04T16:23:15.480",
            "modify_user": "azukovs",
            "create_date": "2020-05-04T16:23:15.477",
            "create_user": "azukovs",
            "subscription_code": "SMALL",
            "client_code": "",
            "fee_code": "154000",
            "event_code": "FEE_PERIODIC",
            "cycle_code": "MONTH",
            "algorithm": "GENERAL",
            "fixed_amount": 1.11000000,
            "percentage": 0.00000000,
            "minimum_amount": 0.00000000,
            "maximum_amount": 0.00000000,
            "fee_currency": "EUR",
            "country_group": "",
            "payment_currency": "",
            "gl": 60215000,
            "account": "",
            "activation_date": "2019-01-01",
            "expiration_date": null,
            "fee_status": "",
            "urgency": "",
            "client_statuses": "",
            "fee_code_description": "e-Wallet management service",
            "fee_dates_status": "ACTIVE"
        }
    ]
}

Нужно разобрать и сложить в базу каждый элемент массива как отдельную строку разбитую по колонкам. Количество элементов массива меняется.

 

Как реализовать?
Возможно, очень плохо искал решение, но не наткнулся.

Нравится

6 комментариев

Здравствуйте! Вам необходимо написать свой обработчик данного объекта и в элементе процесса скрипт обрабатывать данный json.

Олег, пример такого БП —  CampaignCreateLeadProcess, где в функции CreateLead обрабатывают:

	var jsonValue = StepEntity.GetTypedColumnValue<string>("JSON");
	JObject jsonObject = Terrasoft.Common.Json.Json.Deserialize(jsonValue) as JObject;
	if (jsonObject != null) {
		JObject jsonData = jsonObject["addInfo"] as JObject;
		if (jsonData != null) {
			return jsonData["CreateLeadDefaultValues"] as JArray;
		}
	}

А вот пример, как объект из JSON приводят к конкретному типу (а именно фильтрам Terrasoft.Nui.ServiceModel.DataContract.Filters).

Смотрите, сначала создаете объектную модель под свой json

затем метод обработчик:
 

public class Error
    {
    }
 
    public class Datum
    {
 
        [JsonProperty("id")]
        public int Id { get; set; }
 
        [JsonProperty("uid")]
        public string Uid { get; set; }
 
        [JsonProperty("version")]
        public int Version { get; set; }
 
        [JsonProperty("state")]
        public int State { get; set; }
 
        [JsonProperty("modify_date")]
        public DateTime ModifyDate { get; set; }
 
        [JsonProperty("modify_user")]
        public string ModifyUser { get; set; }
 
        [JsonProperty("create_date")]
        public DateTime CreateDate { get; set; }
 
        [JsonProperty("create_user")]
        public string CreateUser { get; set; }
 
        [JsonProperty("subscription_code")]
        public string SubscriptionCode { get; set; }
 
        [JsonProperty("client_code")]
        public string ClientCode { get; set; }
 
        [JsonProperty("fee_code")]
        public string FeeCode { get; set; }
 
        [JsonProperty("event_code")]
        public string EventCode { get; set; }
 
        [JsonProperty("cycle_code")]
        public string CycleCode { get; set; }
 
        [JsonProperty("algorithm")]
        public string Algorithm { get; set; }
 
        [JsonProperty("fixed_amount")]
        public double FixedAmount { get; set; }
 
        [JsonProperty("percentage")]
        public double Percentage { get; set; }
 
        [JsonProperty("minimum_amount")]
        public double MinimumAmount { get; set; }
 
        [JsonProperty("maximum_amount")]
        public double MaximumAmount { get; set; }
 
        [JsonProperty("fee_currency")]
        public string FeeCurrency { get; set; }
 
        [JsonProperty("country_group")]
        public string CountryGroup { get; set; }
 
        [JsonProperty("payment_currency")]
        public string PaymentCurrency { get; set; }
 
        [JsonProperty("gl")]
        public int Gl { get; set; }
 
        [JsonProperty("account")]
        public string Account { get; set; }
 
        [JsonProperty("activation_date")]
        public string ActivationDate { get; set; }
 
        [JsonProperty("expiration_date")]
        public object ExpirationDate { get; set; }
 
        [JsonProperty("fee_status")]
        public string FeeStatus { get; set; }
 
        [JsonProperty("urgency")]
        public string Urgency { get; set; }
 
        [JsonProperty("client_statuses")]
        public string ClientStatuses { get; set; }
 
        [JsonProperty("fee_code_description")]
        public string FeeCodeDescription { get; set; }
 
        [JsonProperty("fee_dates_status")]
        public string FeeDatesStatus { get; set; }
    }
 
    public class MyClass
    {
 
        [JsonProperty("status")]
        public string Status { get; set; }
 
        [JsonProperty("error_description")]
        public string ErrorDescription { get; set; }
 
        [JsonProperty("error")]
        public Error Error { get; set; }
 
        [JsonProperty("data_type")]
        public string DataType { get; set; }
 
        [JsonProperty("total_records")]
        public int TotalRecords { get; set; }
 
        [JsonProperty("data")]
        public IList<Datum> Data { get; set; }
    }
 
 public void MyMethod(string jsonValue)
        {
            var myClass = JsonConvert.DeserializeObject<MyClass>(jsonValue);
        }

вот готовое решение для Вашего случая

Нигрескул Алексей,

Вероятно, ответ очевиден для знающих людей, но как мне это применить в БП? ( Да я не программист, поэтому и задаю такие вопросы :) ) 

Добавить комментарий

Зверев Александр,

У меня не находит такого процесса :(

У меня в 7.16.1 есть. Собственно, это весь его код, в БП запускается первая функция:

 

public virtual void CreateLead() {
	var logger = global::Common.Logging.LogManager.GetLogger(this.Schema.Name);
	var targetInfoCollection = TargetInfoCollection as IEnumerable<KeyValuePair<Guid, Guid>>;
	if (targetInfoCollection != null) {
		EntitySchema leadSchema = UserConnection.EntitySchemaManager.GetInstanceByName("Lead");
		Dictionary<string, object> nameValuePairs = GetDefaultColumns(LeadStepId);
		int counter = 0;
		List<Guid> targetIdCollection = new List<Guid>();
		foreach (KeyValuePair<Guid, Guid> targetInfo in targetInfoCollection) {
			Entity leadEntity = leadSchema.CreateEntity(UserConnection);
			leadEntity.SetDefColumnValues();
			leadEntity.SetColumnValue("StartLeadManagementProcess", false);
			leadEntity.SetColumnValue("QualifiedContactId", targetInfo.Value);
			foreach (KeyValuePair<string, object> pair in nameValuePairs) {
				EntitySchemaColumn column = leadSchema.Columns.FindByName(pair.Key);
				if (column != null) {
					leadEntity.SetColumnValue(column, pair.Value);
				}
			}
			try {
				if (leadEntity.Save()) {
					targetIdCollection.Add(targetInfo.Key);
					if (++counter > 500) {
						SetPassedStepId(LeadStepId, targetIdCollection);
						targetIdCollection.Clear();
						counter = 0;
					}
				}
				leadEntity = null;
			}
			catch (Exception ex) {
				logger.WarnFormat("Lead for contact \"{0}\" can not be created.{2}Error: {1}",
				targetInfo.Value, ex.Message, Environment.NewLine);
			}
		}
		if (targetIdCollection.Count > 0) {
			SetPassedStepId(LeadStepId, targetIdCollection);
		}
	}
}
 
 
public virtual Dictionary<string, object> GetDefaultColumns(Guid StepId) {
	var nameValuePairs = new Dictionary<string, object>();
	EntitySchemaQuery esq = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "CampaignStep");
	esq.AddColumn("JSON");
	esq.AddColumn("Campaign");
	Entity campaignStep = esq.GetEntity(UserConnection, StepId);
	if (campaignStep != null) {
		Guid campaignId = campaignStep.GetTypedColumnValue<Guid>("CampaignId");
		nameValuePairs.Add("Campaign", campaignId);
		JArray jArray = GetAdditionalInfo(campaignStep);
		if (jArray != null && jArray.Count > 0) {
			IList<Dictionary<string, string>> defaultValues = 
				jArray.ToObject<IList<Dictionary<string, string>>>();
			string columnNameKey = "ColumnName";
			string columnValueKey = "ColumnValue";
			foreach (Dictionary<string, string> defaultValue in defaultValues) {
				if (defaultValue.ContainsKey(columnNameKey) &&
					defaultValue.ContainsKey(columnValueKey)) {
						string columnName = defaultValue[columnNameKey];
						string columnValue = defaultValue[columnValueKey];
						if (columnValue != null && !nameValuePairs.ContainsKey(columnName)) {
							nameValuePairs.Add(columnName, (object)new Guid(columnValue));
						}
				}
			}
		}
	}
	return nameValuePairs;
}
 
 
public virtual JArray GetAdditionalInfo(Entity StepEntity) {
	var jsonValue = StepEntity.GetTypedColumnValue<string>("JSON");
	JObject jsonObject = Terrasoft.Common.Json.Json.Deserialize(jsonValue) as JObject;
	if (jsonObject != null) {
		JObject jsonData = jsonObject["addInfo"] as JObject;
		if (jsonData != null) {
			return jsonData["CreateLeadDefaultValues"] as JArray;
		}
	}
	return null;
}
 
 
public virtual void SetPassedStepId(Guid passedStepId, IEnumerable<Guid> targetIdCollection) {
	Update updateQuery = new Update(UserConnection, "CampaignTarget")
		.Set("PassedStepId", Column.Parameter(passedStepId))
		.Where("Id").In(Column.Parameters(targetIdCollection)) as Update;
	updateQuery.Execute();
}

Но без программирования разобраться будет тяжело, весь процесс состоит из одного блока-скрипта, запускающего функцию, которая работает совсем с другим по структуре JSON, не как у Вас.

 

Лучше разбираться с кодом Алексея. 

Показать все комментарии