Обработка вложенных объектов в JSON

DevOps

Client
Регистрация
30.11.2020
Сообщения
496
Благодарностей
314
Баллы
63
Добрый день форум
Подскажите как решить небольшой затык
Получаю данные по API десериализую и все идет нормально до следующего класса

C#:
 public class Root
    {
        public string handle { get; set; }
        public List<object> vcardArray { get; set; }
        public List<string> roles { get; set; }
        public List<Entity> entities { get; set; }
        public string objectClassName { get; set; }
    }
Если для получения значения достаточно этого handle
C#:
    var objectdata = JsonConvert.DeserializeObject<Root>(result);
    string handle = objectdata.handle;
То как обработать "вложку" public List<object> vcardArray никак не допру.
Подскажите как "разложить" объект на составляющие
Юзаю Newtonsoft.Json, но это не принципиально, могу перейти и на стандартное решение System.Text.Json;
Спасибо
 

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Добрый день форум
Подскажите как решить небольшой затык
Получаю данные по API десериализую и все идет нормально до следующего класса

C#:
 public class Root
    {
        public string handle { get; set; }
        public List<object> vcardArray { get; set; }
        public List<string> roles { get; set; }
        public List<Entity> entities { get; set; }
        public string objectClassName { get; set; }
    }
Если для получения значения достаточно этого handle
C#:
    var objectdata = JsonConvert.DeserializeObject<Root>(result);
    string handle = objectdata.handle;
То как обработать "вложку" public List<object> vcardArray никак не допру.
Подскажите как "разложить" объект на составляющие
Юзаю Newtonsoft.Json, но это не принципиально, могу перейти и на стандартное решение System.Text.Json;
Спасибо
Как-то так примерно:
C#:
var items = objectdata.vcardArray.ToList();
foreach(var item in items){
    project.SendInfoToLog(item.ToString());
}
 
  • Спасибо
Реакции: DevOps

DevOps

Client
Регистрация
30.11.2020
Сообщения
496
Благодарностей
314
Баллы
63

viol2021

Client
Регистрация
12.01.2021
Сообщения
481
Благодарностей
179
Баллы
43

DevOps

Client
Регистрация
30.11.2020
Сообщения
496
Благодарностей
314
Баллы
63
C#:
{
  "handle" : "45.155.207.0 - 45.155.207.255",
  "startAddress" : "45.155.207.0",
  "endAddress" : "45.155.207.255",
  "ipVersion" : "v4",
  "name" : "RU-ZTVCORP-20200902",
  "type" : "ASSIGNED PA",
  "country" : "RU",
  "parentHandle" : "45.155.204.0 - 45.155.207.255",
  "cidr0_cidrs" : [ {
    "v4prefix" : "45.155.207.0",
    "length" : 24
  } ],
  "entities" : [ {
    "handle" : "IP-RIPE",
    "roles" : [ "registrant" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ORG-ZTV1-RIPE",
    "roles" : [ "registrant" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ZCL3-RIPE",
    "roles" : [ "administrative", "technical" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ZCL3-RIPE",
    "vcardArray" : [ "vcard", [ [ "version", { }, "text", "4.0" ], [ "fn", { }, "text", "ZTV CORP LLC" ], [ "kind", { }, "text", "group" ], [ "adr", {
      "label" : "ul. Romanticheskaya, d. 12\nYaksatovo\nAstrakhanskaya obl.\n416462\nRussia"
    }, "text", [ "", "", "", "", "", "", "" ] ], [ "tel", {
      "type" : "voice"
    }, "text", "+7 999 8000369" ], [ "email", {
      "type" : "email"
    }, "text", "[email protected]" ], [ "email", {
      "type" : "abuse"
    }, "text", "[email protected]" ] ] ],
    "roles" : [ "abuse" ],
    "entities" : [ {
      "handle" : "IP-RIPE",
      "roles" : [ "registrant" ],
      "objectClassName" : "entity"
    } ]
  }
Для создания нужных классов использую https://json2csharp.com/
Пишу в Студии 2022
Юзаю библ Newtonsoft.Json
С этим проблем нет

C#:
 "handle" : "45.155.207.0 - 45.155.207.255",
  "startAddress" : "45.155.207.0",
  "endAddress" : "45.155.207.255",
  "ipVersion" : "v4",
  "name" : "RU-ZTVCORP-20200902",
  "type" : "ASSIGNED PA",
  "country" : "RU",
  "parentHandle" : "45.155.204.0 - 45.155.207.255",
Классы выглядят тактим образом

C#:
public class Cidr0Cidr
{
    public string v4prefix { get; set; }
    public int length { get; set; }
}

public class Entity
{
    public string handle { get; set; }
    public List<string> roles { get; set; }
    public string objectClassName { get; set; }
    public List<object> vcardArray { get; set; }

    public List<Entity> entities { get; set; }

    internal object ToList()
    {
        throw new NotImplementedException();
    }
}

public class Event
{
    public string eventAction { get; set; }
    public DateTime eventDate { get; set; }
}

public class Link
{
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
    public string type { get; set; }
}

public class Notice
{
    public string title { get; set; }
    public List<string> description { get; set; }
    public List<Link> links { get; set; }
}

public class Root
{
    public string handle { get; set; }
    public string startAddress { get; set; }
    public string endAddress { get; set; }
    public string ipVersion { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string country { get; set; }
    public string parentHandle { get; set; }
    public List<Cidr0Cidr> cidr0_cidrs { get; set; }
    public List<Entity> entities { get; set; }
    public List<Link> links { get; set; }
    public List<Event> events { get; set; }
    public List<string> rdapConformance { get; set; }
    public List<Notice> notices { get; set; }
    public string port43 { get; set; }
    public string objectClassName { get; set; }


}
 

viol2021

Client
Регистрация
12.01.2021
Сообщения
481
Благодарностей
179
Баллы
43
C#:
{
  "handle" : "45.155.207.0 - 45.155.207.255",
  "startAddress" : "45.155.207.0",
  "endAddress" : "45.155.207.255",
  "ipVersion" : "v4",
  "name" : "RU-ZTVCORP-20200902",
  "type" : "ASSIGNED PA",
  "country" : "RU",
  "parentHandle" : "45.155.204.0 - 45.155.207.255",
  "cidr0_cidrs" : [ {
    "v4prefix" : "45.155.207.0",
    "length" : 24
  } ],
  "entities" : [ {
    "handle" : "IP-RIPE",
    "roles" : [ "registrant" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ORG-ZTV1-RIPE",
    "roles" : [ "registrant" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ZCL3-RIPE",
    "roles" : [ "administrative", "technical" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ZCL3-RIPE",
    "vcardArray" : [ "vcard", [ [ "version", { }, "text", "4.0" ], [ "fn", { }, "text", "ZTV CORP LLC" ], [ "kind", { }, "text", "group" ], [ "adr", {
      "label" : "ul. Romanticheskaya, d. 12\nYaksatovo\nAstrakhanskaya obl.\n416462\nRussia"
    }, "text", [ "", "", "", "", "", "", "" ] ], [ "tel", {
      "type" : "voice"
    }, "text", "+7 999 8000369" ], [ "email", {
      "type" : "email"
    }, "text", "[email protected]" ], [ "email", {
      "type" : "abuse"
    }, "text", "[email protected]" ] ] ],
    "roles" : [ "abuse" ],
    "entities" : [ {
      "handle" : "IP-RIPE",
      "roles" : [ "registrant" ],
      "objectClassName" : "entity"
    } ]
  }
Для создания нужных классов использую https://json2csharp.com/
Пишу в Студии 2022
Юзаю библ Newtonsoft.Json
С этим проблем нет

C#:
 "handle" : "45.155.207.0 - 45.155.207.255",
  "startAddress" : "45.155.207.0",
  "endAddress" : "45.155.207.255",
  "ipVersion" : "v4",
  "name" : "RU-ZTVCORP-20200902",
  "type" : "ASSIGNED PA",
  "country" : "RU",
  "parentHandle" : "45.155.204.0 - 45.155.207.255",
Классы выглядят тактим образом

C#:
public class Cidr0Cidr
{
    public string v4prefix { get; set; }
    public int length { get; set; }
}

public class Entity
{
    public string handle { get; set; }
    public List<string> roles { get; set; }
    public string objectClassName { get; set; }
    public List<object> vcardArray { get; set; }

    public List<Entity> entities { get; set; }

    internal object ToList()
    {
        throw new NotImplementedException();
    }
}

public class Event
{
    public string eventAction { get; set; }
    public DateTime eventDate { get; set; }
}

public class Link
{
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
    public string type { get; set; }
}

public class Notice
{
    public string title { get; set; }
    public List<string> description { get; set; }
    public List<Link> links { get; set; }
}

public class Root
{
    public string handle { get; set; }
    public string startAddress { get; set; }
    public string endAddress { get; set; }
    public string ipVersion { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string country { get; set; }
    public string parentHandle { get; set; }
    public List<Cidr0Cidr> cidr0_cidrs { get; set; }
    public List<Entity> entities { get; set; }
    public List<Link> links { get; set; }
    public List<Event> events { get; set; }
    public List<string> rdapConformance { get; set; }
    public List<Notice> notices { get; set; }
    public string port43 { get; set; }
    public string objectClassName { get; set; }


}
Json с ошибкой. Нормальный пришлите
 

DevOps

Client
Регистрация
30.11.2020
Сообщения
496
Благодарностей
314
Баллы
63
Json с ошибкой. Нормальный пришлите
C#:
{
  "handle" : "45.155.207.0 - 45.155.207.255",
  "startAddress" : "45.155.207.0",
  "endAddress" : "45.155.207.255",
  "ipVersion" : "v4",
  "name" : "RU-ZTVCORP-20200902",
  "type" : "ASSIGNED PA",
  "country" : "RU",
  "parentHandle" : "45.155.204.0 - 45.155.207.255",
  "cidr0_cidrs" : [ {
    "v4prefix" : "45.155.207.0",
    "length" : 24
  } ],
  "entities" : [ {
    "handle" : "IP-RIPE",
    "roles" : [ "registrant" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ORG-ZTV1-RIPE",
    "roles" : [ "registrant" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ZCL3-RIPE",
    "roles" : [ "administrative", "technical" ],
    "objectClassName" : "entity"
  }, {
    "handle" : "ZCL3-RIPE",
    "vcardArray" : [ "vcard", [ [ "version", { }, "text", "4.0" ], [ "fn", { }, "text", "ZTV CORP LLC" ], [ "kind", { }, "text", "group" ], [ "adr", {
      "label" : "ul. Romanticheskaya, d. 12\nYaksatovo\nAstrakhanskaya obl.\n416462\nRussia"
    }, "text", [ "", "", "", "", "", "", "" ] ], [ "tel", {
      "type" : "voice"
    }, "text", "+7 999 8000369" ], [ "email", {
      "type" : "email"
    }, "text", "[email protected]" ], [ "email", {
      "type" : "abuse"
    }, "text", "[email protected]" ] ] ],
    "roles" : [ "abuse" ],
    "entities" : [ {
      "handle" : "IP-RIPE",
      "roles" : [ "registrant" ],
      "objectClassName" : "entity"
    } ],
    "objectClassName" : "entity"
  } ],
  "links" : [ {
    "value" : "http://close",
    "rel" : "self",
    "href" : "http://close"
  }, {
    "value" : "http://close",
    "rel" : "copyright",
    "href" : "http://close"
  } ],
  "events" : [ {
    "eventAction" : "last changed",
    "eventDate" : "2022-01-26T13:17:29Z"
  } ],
  "rdapConformance" : [ "cidr0", "UO_level_0" ],
  "notices" : [ {
    "title" : "Filtered",
    "description" : [ "This output has been filtered." ]
  }, {
    "title" : "Source",
    "description" : [ "Objects returned came from source", "UO" ]
  }, {
    "title" : "Terms and Conditions",
    "description" : [ "This is the Database query service. The objects are in UO format." ],
    "links" : [ {
      "value" : "http://close",
      "rel" : "terms-of-service",
      "href" : "http://close",
      "type" : "application/pdf"
    } ]
  } ],
  "port43" : "whois",
  "objectClassName" : "ip network"
}
 

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Для создания нужных классов использую https://json2csharp.com/
Пишу в Студии 2022
Юзаю библ Newtonsoft.Json
Для создания классов в студии, Правка=>Специальная вставка=>Вставить Json
98872


Получаем что-то вроде этого:
C#:
public class Rootobject {
    public string handle { get; set; }
    public string startAddress { get; set; }
    public string endAddress { get; set; }
    public string ipVersion { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string country { get; set; }
    public string parentHandle { get; set; }
    public Cidr0_Cidrs[] cidr0_cidrs { get; set; }
    public Entity[] entities { get; set; }
    public Link[] links { get; set; }
    public Event[] events { get; set; }
    public string[] rdapConformance { get; set; }
    public Notice[] notices { get; set; }
    public string port43 { get; set; }
    public string objectClassName { get; set; }
}

public class Cidr0_Cidrs {
    public string v4prefix { get; set; }
    public int length { get; set; }
}

public class Entity {
    public string handle { get; set; }
    public string[] roles { get; set; }
    public string objectClassName { get; set; }
    public object[] vcardArray { get; set; }
    public Entity1[] entities { get; set; }
}

public class Entity1 {
    public string handle { get; set; }
    public string[] roles { get; set; }
    public string objectClassName { get; set; }
}

public class Link {
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
}

public class Event {
    public string eventAction { get; set; }
    public DateTime eventDate { get; set; }
}

public class Notice {
    public string title { get; set; }
    public string[] description { get; set; }
    public Link1[] links { get; set; }
}

public class Link1 {
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
    public string type { get; set; }
}
vcardArray сидит внутри Entity
 
  • Спасибо
Реакции: DevOps

DevOps

Client
Регистрация
30.11.2020
Сообщения
496
Благодарностей
314
Баллы
63
Для создания классов в студии, Правка=>Специальная вставка=>Вставить Json
Посмотреть вложение 98872

Получаем что-то вроде этого:
C#:
public class Rootobject {
    public string handle { get; set; }
    public string startAddress { get; set; }
    public string endAddress { get; set; }
    public string ipVersion { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string country { get; set; }
    public string parentHandle { get; set; }
    public Cidr0_Cidrs[] cidr0_cidrs { get; set; }
    public Entity[] entities { get; set; }
    public Link[] links { get; set; }
    public Event[] events { get; set; }
    public string[] rdapConformance { get; set; }
    public Notice[] notices { get; set; }
    public string port43 { get; set; }
    public string objectClassName { get; set; }
}

public class Cidr0_Cidrs {
    public string v4prefix { get; set; }
    public int length { get; set; }
}

public class Entity {
    public string handle { get; set; }
    public string[] roles { get; set; }
    public string objectClassName { get; set; }
    public object[] vcardArray { get; set; }
    public Entity1[] entities { get; set; }
}

public class Entity1 {
    public string handle { get; set; }
    public string[] roles { get; set; }
    public string objectClassName { get; set; }
}

public class Link {
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
}

public class Event {
    public string eventAction { get; set; }
    public DateTime eventDate { get; set; }
}

public class Notice {
    public string title { get; set; }
    public string[] description { get; set; }
    public Link1[] links { get; set; }
}

public class Link1 {
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
    public string type { get; set; }
}
vcardArray сидит внутри Entity
Спасибо, очень удобно, поэтому и сел за Студию
Но вопрос в заголовке- как распарсить объект в классе :-)
Ну не догоняю никак
PS После вставки по Вашей инструкции не внимательно глянул классы, теперь все понятно, спасибо
 
Последнее редактирование:

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Вы писали что используете онлайн конвертер.
Для создания нужных классов использую https://json2csharp.com/
Но при этом используете студию.
А для сложных объектов - он кривой, не всегда отдает то что нужно.
Из-за чего я попытался помочь Вам тем, что объяснил как можно сгенерировать валидный код через студию.

К сожалению, у меня не было в тот момент времени, чтобы более подробно описывать что к чему, из-за чего я просто постарался быстро, но более-менее понятно изложить в чем дело. Простите, что не объяснил сразу в чем проблема.

Хорошего вечера.
Рад, что проблема была решена.
 
  • Спасибо
Реакции: DevOps

DevOps

Client
Регистрация
30.11.2020
Сообщения
496
Благодарностей
314
Баллы
63
Вы писали что используете онлайн конвертер.

Но при этом используете студию.
А для сложных объектов - он кривой, не всегда отдает то что нужно.
Из-за чего я попытался помочь Вам тем, что объяснил как можно сгенерировать валидный код через студию.

К сожалению, у меня не было в тот момент времени, чтобы более подробно описывать что к чему, из-за чего я просто постарался быстро, но более-менее понятно изложить в чем дело. Простите, что не объяснил сразу в чем проблема.

Хорошего вечера.
Рад, что проблема была решена.
Да спасибо, но один хер вытащить оттуда ничего не могу,хз что за ублюдок такой массив создавал
 

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Да спасибо, но один хер вытащить оттуда ничего не могу,хз что за ублюдок такой массив создавал
Как не можете?

C#:
var root= JsonConvert.DeserializeObject<Rootobject>(result);
var ob = root.entities; // все сущности объекты
var array = ob[0].vcardArray; // массив первой сущности
далее перебираем его в цикле
 
  • Спасибо
Реакции: DevOps

DevOps

Client
Регистрация
30.11.2020
Сообщения
496
Благодарностей
314
Баллы
63
Как не можете?

C#:
var root= JsonConvert.DeserializeObject<Rootobject>(result);
var ob = root.entities; // все сущности объекты
var array = ob[0].vcardArray; // массив первой сущности
далее перебираем его в цикле
Все что я за эти 2 суток сумел вытащить это System.Collections.Generic.List`1[System.Object]
или эксепшен System.NullReferenceException: "Object reference not set to an instance of an object."
с JSON ранее не работал, вот понадобилось и "воткнулся". Зачем епта такая вложеность вообще нужна хз
 

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Все что я за эти 2 суток сумел вытащить это System.Collections.Generic.List`1[System.Object]
или эксепшен System.NullReferenceException: "Object reference not set to an instance of an object."
Вы точно используете в текущий момент код который я предоставил?
Ваш JSON точно такой, как Вы предоставили, или другой?
Сейчас ещё раз повторно проверю - отпишусь минут через 15.
 
  • Спасибо
Реакции: DevOps

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
C#:
string json = project.Variables["json"].Value; // тот json который Вы давали выше
// В общем коде находится код классов без изменений, тот который также бросал выше
Rootobject root = Global.ZennoLab.Json.JsonConvert.DeserializeObject<Rootobject>(json);
//project.SendInfoToLog(string.Format("{0}",root.entities.Length ));
for(int i=0; i<root.entities.Length; i++) {
    var ob = root.entities[i];
    //project.SendInfoToLog(string.Format("{0}",Global.ZennoLab.Json.JsonConvert.SerializeObject(ob,  Global.ZennoLab.Json.Formatting.Indented)));
    if(ob.vcardArray!=null){
        var items = ob.vcardArray;
        foreach(var item in items) {
            // один элемент из vcardArray - здесь уже с ним можно делать все что угодно
            project.SendInfoToLog(string.Format("{0}",Global.ZennoLab.Json.JsonConvert.SerializeObject(item,  Global.ZennoLab.Json.Formatting.Indented)));
        }
    }
}
 
  • Спасибо
Реакции: DevOps

DevOps

Client
Регистрация
30.11.2020
Сообщения
496
Благодарностей
314
Баллы
63
Вы точно используете в текущий момент код который я предоставил?
Ваш JSON точно такой, как Вы предоставили, или другой?
Сейчас ещё раз повторно проверю - отпишусь минут через 15.
Грубо черновик, не пинайте, на тестах не заморачиваюсь
C#:
using System.Net;
using Newtonsoft.Json;


object locker = new object();
object locker_out = new object();
string path_in = @"C:\Users\Mayersk\Desktop\IN.txt";
string path_out = @"C:\Users\Mayersk\Desktop\OUT.txt";
int threads = 10;
Queue<string> prox = new Queue<string>();
string[] lines = File.ReadAllLines(path_in);
Queue<string> q = new Queue<string>();
string line = string.Empty;
string startAddress = string.Empty;
foreach (string ptf in lines)
{
    q.Enqueue(ptf);
}
for (int i = 0; i < threads; i++)
{
    Thread myThread = new Thread(() => Parser(q));
    myThread.Start();
}
void Parser(Queue<string> q)
{
    try
    {
        int count = q.Count;

        for (int i = 0; i < count; i++)
        {
            lock (locker)
            {
                line = q.Dequeue();
            }
            string lines = line.ToString();
            string[] text = lines.Split(";");
            string ns = text[0].ToString();
            string ip = text[1].ToString();
            
            using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
            {
                client.BaseAddress = new Uri(ip);
                HttpResponseMessage response = client.GetAsync(ip).Result;
                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine();

                var objectdata2 = JsonConvert.DeserializeObject<Entity>(result);
                var root = JsonConvert.DeserializeObject<Rootobject>(result);
                var ob = root.entities;
                var array = ob[0].vcardArray;
                string alfa = array.ToString();

                    Console.WriteLine(alfa);

                string startAddress = root.startAddress;
                string endAddress = root.endAddress;
                string name = root.name;
                string country = root.country;
                string data_out = ns + ";" + ip + ";" + startAddress + "-" + endAddress + ";" + name + ";" + country;

                {
                    Console.WriteLine(data_out);
                }
            }
        }
    }
    catch (Exception Ex)
    {
        Console.WriteLine(Ex);
    }
    
}

public class Rootobject
{
    public string handle { get; set; }
    public string startAddress { get; set; }
    public string endAddress { get; set; }
    public string ipVersion { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string country { get; set; }
    public string parentHandle { get; set; }
    public Cidr0_Cidrs[] cidr0_cidrs { get; set; }
    public Entity[] entities { get; set; }
    public Link[] links { get; set; }
    public Event[] events { get; set; }
    public string[] rdapConformance { get; set; }
    public Notice[] notices { get; set; }
    public string port43 { get; set; }
    public string objectClassName { get; set; }
}

public class Cidr0_Cidrs
{
    public string v4prefix { get; set; }
    public int length { get; set; }
}

public class Entity
{
    public string handle { get; set; }
    public string[] roles { get; set; }
    public string objectClassName { get; set; }
    public object[] vcardArray { get; set; }
    public Entity1[] entities { get; set; }
}

public class Entity1
{
    public string handle { get; set; }
    public string[] roles { get; set; }
    public string objectClassName { get; set; }
}

public class Link
{
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
}

public class Event
{
    public string eventAction { get; set; }
    public DateTime eventDate { get; set; }
}

public class Notice
{
    public string title { get; set; }
    public string[] description { get; set; }
    public Link1[] links { get; set; }
}

public class Link1
{
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
    public string type { get; set; }
}
Тут все собирает, в принципе этого достаточно, но уже задело

C#:
                string startAddress = root.startAddress;
                string endAddress = root.endAddress;
                string name = root.name;
                string country = root.country;
                string data_out = ns + ";" + ip + ";" + startAddress + "-" + endAddress + ";" + name + ";" + country;
 
  • Спасибо
Реакции: BAZAg

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Грубо черновик, не пинайте, на тестах не заморачиваюсь

C#:
using System.Net;
using Newtonsoft.Json;

object locker = new object();
object locker_out = new object();
string path_in = @"C:\Users\Mayersk\Desktop\IN.txt";
string path_out = @"C:\Users\Mayersk\Desktop\OUT.txt";
int threads = 10;
Queue<string> prox = new Queue<string>();
string[] lines = File.ReadAllLines(path_in);
Queue<string> q = new Queue<string>();
string line = string.Empty;
string startAddress = string.Empty;
foreach (string ptf in lines) {
    q.Enqueue(ptf);
}

for (int i = 0; i < threads; i++){
    Thread myThread = new Thread(() => Parser(q));
    myThread.Start();
}

void Parser(Queue<string> q) {
    try {
        int count = q.Count;
        for (int i = 0; i < count; i++) {

            lock (locker) {
                line = q.Dequeue();
            }

            string lines = line.ToString();
            string[] text = lines.Split(";");
            string ns = text[0].ToString();
            string ip = text[1].ToString();

            using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })) {
                client.BaseAddress = new Uri(ip);
                HttpResponseMessage response = client.GetAsync(ip).Result;
                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine();
               
                var objectdata2 = JsonConvert.DeserializeObject<Entity>(result);
                var root = JsonConvert.DeserializeObject<Rootobject>(result);
                var ob = root.entities;
                var array = ob[0].vcardArray;
                string alfa = array.ToString();
                Console.WriteLine(alfa);

                string startAddress = root.startAddress;
                string endAddress = root.endAddress;
                string name = root.name;
                string country = root.country;
                string data_out = ns + ";" + ip + ";" + startAddress + "-" + endAddress + ";" + name + ";" + country;
               
                Console.WriteLine(data_out);
            }
        }
    }
    catch (Exception Ex){
        Console.WriteLine(Ex);
    }
}

public class Rootobject{
    public string handle { get; set; }
    public string startAddress { get; set; }
    public string endAddress { get; set; }
    public string ipVersion { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string country { get; set; }
    public string parentHandle { get; set; }
    public Cidr0_Cidrs[] cidr0_cidrs { get; set; }
    public Entity[] entities { get; set; }
    public Link[] links { get; set; }
    public Event[] events { get; set; }
    public string[] rdapConformance { get; set; }
    public Notice[] notices { get; set; }
    public string port43 { get; set; }
    public string objectClassName { get; set; }

}
public class Cidr0_Cidrs{
    public string v4prefix { get; set; }
    public int length { get; set; }
}
public class Entity{
    public string handle { get; set; }
    public string[] roles { get; set; }
    public string objectClassName { get; set; }
    public object[] vcardArray { get; set; }
    public Entity1[] entities { get; set; }
}
public class Entity1{
    public string handle { get; set; }
    public string[] roles { get; set; }
    public string objectClassName { get; set; }
}
public class Link{
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
}
public class Event{
    public string eventAction { get; set; }
    public DateTime eventDate { get; set; }
}
public class Notice{
    public string title { get; set; }
    public string[] description { get; set; }
    public Link1[] links { get; set; }

}
public class Link1 {
    public string value { get; set; }
    public string rel { get; set; }
    public string href { get; set; }
    public string type { get; set; }

}
Тут все собирает, в принципе этого достаточно, но уже задело
C#:
string startAddress = root.startAddress;
string endAddress = root.endAddress;
string name = root.name;
string country = root.country;
string data_out = ns + ";" + ip + ";" + startAddress + "-" + endAddress + ";" + name + ";" + country;
Я бы все же рекомендовал отделить запрос от обработки результата, выделив эти блоки кода в отдельные методы.
Хотя, с другой стороны, если все работает - оставляйте как есть и все дела.

C#:
public static string Get(string ip){
    string result = string.Empty;
    try{
        using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })) {
            client.BaseAddress = new Uri(ip);
            var response = client.GetAsync(ip).Result;
            result = response.Content.ReadAsStringAsync().Result;
        }
    }
    catch {
        result = string.Empty;
    }
    return result;
}
C#:
public static string Data(string ns, string ip, string json){
    string[] out_data = new string[5];
    out_data[0] = ns;
    out_data[1] = ip;
    string json = Get(ip); // вызов get
    if(!string.IsNullOrEmpty(json)) {
        var root = JsonConvert.DeserializeObject<Rootobject>(json);
        var ob = root.entities;
        var array = ob[0].vcardArray; //хм.. нигде не используется... + проверка на null нужна будет
        string alfa = array.ToString();
        string startAddress = root.startAddress;
        string endAddress = root.endAddress;
        string name = root.name;
        string country = root.country;
        out_data[2] = startAddress + "-" + endAddress;
        out_data[3] = name;
        out_data[4] = country;
    }
    return string.Join(";", out_data);        
}
 
  • Спасибо
Реакции: Dome4ta1

vedi108

Client
Регистрация
22.08.2022
Сообщения
16
Благодарностей
3
Баллы
3
Всем здравия! Форумчане , помогите к кодом. Вообще пока не владею кодом, так, поверхностно совсем.
Есть задача распарсить json в переменные.
пользуюсь этим кодом
C#:
//парсим json
project.Json.FromString(project.Variables["token_json"].Value);
//берем нужное св-во в переменную
project.Variables["conf_signal"].Value = project.Json.conf_signal;
но этот код работает исключительно со строками, обрабатывать числа он не хочет! Что делать, как решить задачу? например чтобы данные из запроса корректно обрабатывать и класть в переменные
C#:
{
    "ret_code": 0,
    "ret_msg": "OK",
    "time_now": "1666706180.267360",
    "rate_limit_status": 118,
    "rate_limit_reset_ms": 1666706180258,
    "cum": -8.22451243,
}
 

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Всем здравия! Форумчане , помогите к кодом. Вообще пока не владею кодом, так, поверхностно совсем.
Есть задача распарсить json в переменные.
пользуюсь этим кодом
C#:
//парсим json
project.Json.FromString(project.Variables["token_json"].Value);
//берем нужное св-во в переменную
project.Variables["conf_signal"].Value = project.Json.conf_signal;
но этот код работает исключительно со строками, обрабатывать числа он не хочет! Что делать, как решить задачу? например чтобы данные из запроса корректно обрабатывать и класть в переменные
C#:
{
    "ret_code": 0,
    "ret_msg": "OK",
    "time_now": "1666706180.267360",
    "rate_limit_status": 118,
    "rate_limit_reset_ms": 1666706180258,
    "cum": -8.22451243,
}
Внутри Вашего исходного json нет поля conf_signal
Можете попробовать использовать примерно такой код, чтобы с одной стороны не появлялись ошибки, если поля нет.
С другой, чтобы привести не известный тип данных к строке.
C#:
string json = project.Variables["json"].Value;
string line = string.Empty;
try {
    var data = Global.ZennoLab.Json.JsonConvert.DeserializeObject<dynamic>(json); //парсим json
    string member = "time_now";
    try {
        line = data[member].ToObject<string>();//берем нужное св-во в переменную
    }
    catch {
        project.SendWarningToLog(string.Format("member не найден: {0}",member),true);    
    }
}
catch {
    project.SendWarningToLog("JSON не валидный", true);
}
project.Variables["conf_signal"].Value = line;// сохранили результат
99224
 
Последнее редактирование:

vedi108

Client
Регистрация
22.08.2022
Сообщения
16
Благодарностей
3
Баллы
3
Внутри Вашего исходного json нет поля conf_signal
Можете попробовать использовать примерно такой код, чтобы с одной стороны не появлялись ошибки, если поля нет.
С другой, чтобы привести не известный тип данных к строке.
C#:
string json = project.Variables["json"].Value;
string line = string.Empty;
try {
    var data = Global.ZennoLab.Json.JsonConvert.DeserializeObject<dynamic>(json); //парсим json
    string member = "time_now";
    try {
        line = data[member].ToObject<string>();//берем нужное св-во в переменную
    }
    catch {
        project.SendWarningToLog(string.Format("member не найден: {0}",member),true);   
    }
}
catch {
    project.SendWarningToLog("JSON не валидный", true);
}
project.Variables["conf_signal"].Value = line;// сохранили результат
Посмотреть вложение 99224
Благодарствую,
А если мне нужно вытащить выборочно данные и положить их в переменные? , например:
"time_now" в "time"
"user_id" в "user"
"time_now" в "time"

так чтобы это всё было реализовано в одном кубике

C#:
{
    "ret_code": 0,
    "ret_msg": "OK",
    "result": [
        {
            "user_id": 41548293,
            "mode": "BothSide"
        },
        {
            "user_id": ,
            "mode": ""
        }
    ],
    "ext_code": "",
    "ext_info": "",
    "time_now": "1667653941.734579",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1667653941731,
    "rate_limit": 120
}
 

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Благодарствую,
А если мне нужно вытащить выборочно данные и положить их в переменные? , например:
"time_now" в "time"
"user_id" в "user"
"time_now" в "time"

так чтобы это всё было реализовано в одном кубике

C#:
{
    "ret_code": 0,
    "ret_msg": "OK",
    "result": [
        {
            "user_id": 41548293,
            "mode": "BothSide"
        },
        {
            "user_id": ,
            "mode": ""
        }
    ],
    "ext_code": "",
    "ext_info": "",
    "time_now": "1667653941.734579",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1667653941731,
    "rate_limit": 120
}
Перечислите имена переменных куда сохранить эти два user_id.
Что делать если там будет 100 элементов user_id - в какие именно переменные с какими именами Вы хотите их сохранять?
99231
 

vedi108

Client
Регистрация
22.08.2022
Сообщения
16
Благодарностей
3
Баллы
3
Добро. хотел законспирироваться , да ладно...
Вот json-ответ:
JSON:
{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "user_id": 41548293,
            "symbol": "REEFUSDT",
            "side": "Buy",
            "size": 0,
            "position_value": 0,
            "entry_price": 0,
            "liq_price": 0,
            "bust_price": 0,
            "leverage": 10,
            "auto_add_margin": 0,
            "is_isolated": true,
            "position_margin": 0,
            "occ_closing_fee": 0,
            "realised_pnl": 0,
            "cum_realised_pnl": 0,
            "free_qty": 0,
            "tp_sl_mode": "Full",
            "unrealised_pnl": 0,
            "deleverage_indicator": 0,
            "risk_id": 1,
            "stop_loss": 0,
            "take_profit": 0,
            "trailing_stop": 0,
            "position_idx": 1,
            "mode": "BothSide"
        },
        {
            "user_id": 41548293,
            "symbol": "REEFUSDT",
            "side": "Sell",
            "size": 1000,
            "position_value": 5.74,
            "entry_price": 0.00574,
            "liq_price": 0.00608,
            "bust_price": 0.00631,
            "leverage": 10,
            "auto_add_margin": 0,
            "is_isolated": true,
            "position_margin": 0.5740024,
            "occ_closing_fee": 0.003786,
            "realised_pnl": -0.003444,
            "cum_realised_pnl": -0.003444,
            "free_qty": 1000,
            "tp_sl_mode": "Full",
            "unrealised_pnl": -0.005,
            "deleverage_indicator": 2,
            "risk_id": 1,
            "stop_loss": 0,
            "take_profit": 0,
            "trailing_stop": 0,
            "position_idx": 2,
            "mode": "BothSide"
        }
    ],
    "time_now": "1666706175.967156",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1666706175965,
    "rate_limit": 120
}
Задача состоит в том, чтобы выдернуть данные в зависимость от открытой позиции ордера. Если у переменной проекта {-Variable.position_side-} значение "Buy", то спарсить нужно соответствующую часть ответа в json это "side": "Buy", если в {-Variable.position_side-} "Sell", то соответственно "side": "Sell". Если в {-Variable.position_side-} пусто, то и выйти из кубика через красную точку.

Сейчас у меня такая конструкция
C#:
//парсим json
project.Json.FromString(project.Variables["position_json"].Value);
//берем нужное св-во в переменную
project.Variables["position_pnl"].Value = Convert.ToString(project.Json.result[0].unrealised_pnl).Replace(",",".");
project.Variables["position_margin"].Value = Convert.ToString(project.Json.result[0].position_margin).Replace(",",".");
project.Variables["position_side"].Value = Convert.ToString(project.Json.result[0].side);
project.Variables["tmp_signal_old"].Value = Convert.ToString(project.Json.result[0].side);
project.Variables["position_size"].Value = Convert.ToString(project.Json.result[0].size);
project.Variables["position_simbol"].Value = Convert.ToString(project.Json.result[0].symbol);
project.Variables["position_entry_price"].Value = Convert.ToString(project.Json.result[0].entry_price).Replace(",",".");
project.Variables["position_json_utime"].Value = Convert.ToString(project.Json.time_now);
Она меня полностью устраивает за исключением того, что я не знаю как динамически менять в json-пермепенных project.Json.result[0].symbol) номер массива (или как правильно это называется я пока не знаю) с 0 на 1 в зависимости от значения в {-Variable.position_side-}, где 0 это Buy, а 1 это Sell. И как видно в моем примере, у некоторых значений мне нужно менять запятую на точку.
 

BAZAg

Client
Регистрация
08.11.2015
Сообщения
1 767
Благодарностей
2 409
Баллы
113
Добро. хотел законспирироваться , да ладно...
Вот json-ответ:
JSON:
{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "user_id": 41548293,
            "symbol": "REEFUSDT",
            "side": "Buy",
            "size": 0,
            "position_value": 0,
            "entry_price": 0,
            "liq_price": 0,
            "bust_price": 0,
            "leverage": 10,
            "auto_add_margin": 0,
            "is_isolated": true,
            "position_margin": 0,
            "occ_closing_fee": 0,
            "realised_pnl": 0,
            "cum_realised_pnl": 0,
            "free_qty": 0,
            "tp_sl_mode": "Full",
            "unrealised_pnl": 0,
            "deleverage_indicator": 0,
            "risk_id": 1,
            "stop_loss": 0,
            "take_profit": 0,
            "trailing_stop": 0,
            "position_idx": 1,
            "mode": "BothSide"
        },
        {
            "user_id": 41548293,
            "symbol": "REEFUSDT",
            "side": "Sell",
            "size": 1000,
            "position_value": 5.74,
            "entry_price": 0.00574,
            "liq_price": 0.00608,
            "bust_price": 0.00631,
            "leverage": 10,
            "auto_add_margin": 0,
            "is_isolated": true,
            "position_margin": 0.5740024,
            "occ_closing_fee": 0.003786,
            "realised_pnl": -0.003444,
            "cum_realised_pnl": -0.003444,
            "free_qty": 1000,
            "tp_sl_mode": "Full",
            "unrealised_pnl": -0.005,
            "deleverage_indicator": 2,
            "risk_id": 1,
            "stop_loss": 0,
            "take_profit": 0,
            "trailing_stop": 0,
            "position_idx": 2,
            "mode": "BothSide"
        }
    ],
    "time_now": "1666706175.967156",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1666706175965,
    "rate_limit": 120
}
Задача состоит в том, чтобы выдернуть данные в зависимость от открытой позиции ордера. Если у переменной проекта {-Variable.position_side-} значение "Buy", то спарсить нужно соответствующую часть ответа в json это "side": "Buy", если в {-Variable.position_side-} "Sell", то соответственно "side": "Sell". Если в {-Variable.position_side-} пусто, то и выйти из кубика через красную точку.

Сейчас у меня такая конструкция
C#:
//парсим json
project.Json.FromString(project.Variables["position_json"].Value);
//берем нужное св-во в переменную
project.Variables["position_pnl"].Value = Convert.ToString(project.Json.result[0].unrealised_pnl).Replace(",",".");
project.Variables["position_margin"].Value = Convert.ToString(project.Json.result[0].position_margin).Replace(",",".");
project.Variables["position_side"].Value = Convert.ToString(project.Json.result[0].side);
project.Variables["tmp_signal_old"].Value = Convert.ToString(project.Json.result[0].side);
project.Variables["position_size"].Value = Convert.ToString(project.Json.result[0].size);
project.Variables["position_simbol"].Value = Convert.ToString(project.Json.result[0].symbol);
project.Variables["position_entry_price"].Value = Convert.ToString(project.Json.result[0].entry_price).Replace(",",".");
project.Variables["position_json_utime"].Value = Convert.ToString(project.Json.time_now);
Она меня полностью устраивает за исключением того, что я не знаю как динамически менять в json-пермепенных project.Json.result[0].symbol) номер массива (или как правильно это называется я пока не знаю) с 0 на 1 в зависимости от значения в {-Variable.position_side-}, где 0 это Buy, а 1 это Sell. И как видно в моем примере, у некоторых значений мне нужно менять запятую на точку.
Так просто собирайте данные в таблицу, а дальше уже делайте с ними все что считаете нужным.
Вот пример:
C#:
string json = project.Variables["json"].Value;
project.Json.FromString(json);
var tb = project.Tables["tb"];
if(project.Json.result.Count > 0) {
    project.SendInfoToLog(string.Format(@"Найдено столько-то результатов: {0}", project.Json.result.Count));
    for(int i = 0;i<project.Json.result.Count;i++) {
        string[] row = new string[25];
        var item = project.Json.result[i]; // взяли элемент с массива
        row[0] = item.user_id != null ? item.user_id.ToString() : string.Empty;
        row[1] = item.symbol != null ? item.symbol.ToString() : string.Empty;
        row[2] = item.side != null ? item.side.ToString() : string.Empty;
        row[3] = item.size != null ? item.size.ToString() : string.Empty;
        row[4] = item.position_value != null ? item.position_value.ToString() : string.Empty;
        row[5] = item.entry_price != null ? item.entry_price.ToString() : string.Empty;
        row[6] = item.liq_price != null ? item.liq_price.ToString() : string.Empty;
        row[7] = item.bust_price != null ? item.bust_price.ToString() : string.Empty;
        row[8] = item.leverage != null ? item.leverage.ToString() : string.Empty;
        row[9] = item.auto_add_margin != null ? item.auto_add_margin.ToString() : string.Empty;
        row[10] = item.is_isolated != null ? item.is_isolated.ToString() : string.Empty;
        row[11] = item.position_margin != null ? item.position_margin.ToString() : string.Empty;       
        row[12] = item.occ_closing_fee != null ? item.occ_closing_fee.ToString() : string.Empty;
        row[13] = item.realised_pnl != null ? item.realised_pnl.ToString() : string.Empty;
        row[14] = item.cum_realised_pnl != null ? item.cum_realised_pnl.ToString() : string.Empty;
        row[15] = item.free_qty != null ? item.free_qty.ToString() : string.Empty;
        row[16] = item.tp_sl_mode != null ? item.tp_sl_mode.ToString() : string.Empty;       
        row[17] = item.unrealised_pnl != null ? item.unrealised_pnl.ToString() : string.Empty;
        row[18] = item.deleverage_indicator != null ? item.deleverage_indicator.ToString() : string.Empty;
        row[19] = item.risk_id != null ? item.risk_id.ToString() : string.Empty;
        row[20] = item.stop_loss != null ? item.stop_loss.ToString() : string.Empty;       
        row[21] = item.take_profit != null ? item.take_profit.ToString() : string.Empty;
        row[22] = item.trailing_stop != null ? item.trailing_stop.ToString() : string.Empty;
        row[23] = item.position_idx != null ? item.position_idx.ToString() : string.Empty;
        row[24] = item.mode != null ? item.mode.ToString() : string.Empty;       
        if(!string.IsNullOrEmpty(row[2])) tb.AddRow(row);       
    }
}
99243
 
  • Спасибо
Реакции: vedi108 и Alexmd

Alexmd

Client
Регистрация
10.12.2018
Сообщения
1 021
Благодарностей
1 385
Баллы
113
Она меня полностью устраивает за исключением того, что я не знаю как динамически менять в json-пермепенных project.Json.result[0].symbol) номер массива (или как правильно это называется я пока не знаю) с 0 на 1 в зависимости от значения в {-Variable.position_side-}, где 0 это Buy, а 1 это Sell.
C#:
int side;
//определю массив, данные из которого нужно взять
switch(project.Variables["position_side"].Value){
    case "Buy":  { side = 0; break; }
    case "Sell": { side = 1; break; }
    default:throw new Exception(@"Неожидаемое значение переменной ""position_side"":  ");
}
//парсим json
project.Json.FromString(project.Variables["position_json"].Value);
//берем нужное св-во в переменную
project.Variables["position_pnl"].Value = Convert.ToString(project.Json.result[side].unrealised_pnl).Replace(",",".");
project.Variables["position_margin"].Value = Convert.ToString(project.Json.result[side].position_margin).Replace(",",".");
project.Variables["position_side"].Value = Convert.ToString(project.Json.result[side].side);
project.Variables["tmp_signal_old"].Value = Convert.ToString(project.Json.result[side].side);
project.Variables["position_size"].Value = Convert.ToString(project.Json.result[side].size);
project.Variables["position_simbol"].Value = Convert.ToString(project.Json.result[side].symbol);
project.Variables["position_entry_price"].Value = Convert.ToString(project.Json.result[side].entry_price).Replace(",",".");
project.Variables["position_json_utime"].Value = Convert.ToString(project.Json.time_now);
 
  • Спасибо
Реакции: nik-n, vedi108 и BAZAg

vedi108

Client
Регистрация
22.08.2022
Сообщения
16
Благодарностей
3
Баллы
3
Так просто собирайте данные в таблицу, а дальше уже делайте с ними все что считаете нужным.
Вот пример:
C#:
string json = project.Variables["json"].Value;
project.Json.FromString(json);
var tb = project.Tables["tb"];
if(project.Json.result.Count > 0) {
    project.SendInfoToLog(string.Format(@"Найдено столько-то результатов: {0}", project.Json.result.Count));
    for(int i = 0;i<project.Json.result.Count;i++) {
        string[] row = new string[25];
        var item = project.Json.result[i]; // взяли элемент с массива
        row[0] = item.user_id != null ? item.user_id.ToString() : string.Empty;
        row[1] = item.symbol != null ? item.symbol.ToString() : string.Empty;
        row[2] = item.side != null ? item.side.ToString() : string.Empty;
        row[3] = item.size != null ? item.size.ToString() : string.Empty;
        row[4] = item.position_value != null ? item.position_value.ToString() : string.Empty;
        row[5] = item.entry_price != null ? item.entry_price.ToString() : string.Empty;
        row[6] = item.liq_price != null ? item.liq_price.ToString() : string.Empty;
        row[7] = item.bust_price != null ? item.bust_price.ToString() : string.Empty;
        row[8] = item.leverage != null ? item.leverage.ToString() : string.Empty;
        row[9] = item.auto_add_margin != null ? item.auto_add_margin.ToString() : string.Empty;
        row[10] = item.is_isolated != null ? item.is_isolated.ToString() : string.Empty;
        row[11] = item.position_margin != null ? item.position_margin.ToString() : string.Empty;      
        row[12] = item.occ_closing_fee != null ? item.occ_closing_fee.ToString() : string.Empty;
        row[13] = item.realised_pnl != null ? item.realised_pnl.ToString() : string.Empty;
        row[14] = item.cum_realised_pnl != null ? item.cum_realised_pnl.ToString() : string.Empty;
        row[15] = item.free_qty != null ? item.free_qty.ToString() : string.Empty;
        row[16] = item.tp_sl_mode != null ? item.tp_sl_mode.ToString() : string.Empty;      
        row[17] = item.unrealised_pnl != null ? item.unrealised_pnl.ToString() : string.Empty;
        row[18] = item.deleverage_indicator != null ? item.deleverage_indicator.ToString() : string.Empty;
        row[19] = item.risk_id != null ? item.risk_id.ToString() : string.Empty;
        row[20] = item.stop_loss != null ? item.stop_loss.ToString() : string.Empty;      
        row[21] = item.take_profit != null ? item.take_profit.ToString() : string.Empty;
        row[22] = item.trailing_stop != null ? item.trailing_stop.ToString() : string.Empty;
        row[23] = item.position_idx != null ? item.position_idx.ToString() : string.Empty;
        row[24] = item.mode != null ? item.mode.ToString() : string.Empty;      
        if(!string.IsNullOrEmpty(row[2])) tb.AddRow(row);      
    }
}
Посмотреть вложение 99243
Спасибо за код , сильно пригодился
 
  • Спасибо
Реакции: BAZAg

Кто просматривает тему: (Всего: 1, Пользователи: 0, Гости: 1)