1

how can i convert all JArray in json string to object[] in c# Where ever it was in child or child of child now if i want to convert a simple json with JArray to object[]

if my json like this i use

json = "{data:{'a':1008,'b':111111,'c':['data1','data2']}}";

  object Data = JsonConvert.DeserializeObject<object>(json,
      new JsonSerializerSettings
      {
          NullValueHandling = NullValueHandling.Ignore
  });



Newtonsoft.Json.Linq.JArray x = (Newtonsoft.Json.Linq.JArray)Data["c"];
object[] xdata = x.ToObject<object[]>();

and that's work what i need it convert all the JArray in Json string to object[] in children too or children of child

so if i have string like this

json = "{data:{'a':1008,'b':111111,'c':['e':['f':['ccc','bbb'],'RRR'],'data2']}}";

if i want to convert it to normal object array i need to loop on children of "f" JArray and check every child if it's JArray if it's convert

but this is classical method if child have jArray child ... etc

i thing there is a good solution in JsonConverter but i dont have good knowledge on it

public class MyObjectConverter : JsonConverter
{
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{

}

 etc....
}

or mabye by another solution there without JsonConverter why i need some idea because might i will make 10 loop or more for convert all JArray to Object[] using traditional methods

narcos
  • 11
  • 1
  • 3
  • Just deserialize it to a standard poco concrete class, there are many (100s of thousands of examples) on the internet and stackoverflow.com – TheGeneral Aug 26 '20 at 09:22
  • @MichaelRandall I Can't use this because `f` data like random data not static some time there is child have `JArray` some time not some time children of child have two `JArray` – narcos Aug 26 '20 at 09:35
  • If you have a `JObject` or `JArray` with no predefined schema, you can convert it to vanilla .Net objects (dictionaries, lists or primitives) by using `JsonHelper.ToObject()` from [this answer](https://stackoverflow.com/a/19140420/3744182) to [How do I use JSON.NET to deserialize into nested/recursive Dictionary and List?](https://stackoverflow.com/q/5546142/3744182). – dbc Aug 26 '20 at 15:47
  • 1
    @dbc thank for that's link i think that gonna help – narcos Aug 27 '20 at 07:46

1 Answers1

1

Why not using JObject instead of object[] so it will fix the issue in child array

var value = JObject.Parse(json);
var c = value["data"]["c"];

variable c will be JArray type

var objectArray = c.ToObject<List<object>>().ToArray();

If you really want to achieve the result as an object[] the objectArray variable is the answer.

KhailXpro
  • 298
  • 1
  • 3
  • 10