Convert nested JSON Dictionary<string, JValue> to excel worksheet
The json strings that I deal with have x levels and each time they are different json strings.
Json string:
[{
"nombreId":1016,
"nombre":John,
"proyectos":[
{"proyectoId":1,"nombre":ProyectoEmpleados},
{"proyectoId":20,"nombre":ProyectoNominas},
],
"nombreId":1056,
"nombre":Sara,
"proyectos":[
{"proyectoId":22,"nombre":ProyectoContabilidad},
{"proyectoId":nombre,"nombre":ProyectoNominas},
]
}]
I have parsed a nested json string to Dictionary<string, JValue> like this:
public class JsonColeccionCampo
{
private readonly Dictionary<string, JValue> campos;
public JsonColeccionCampo(JToken token)
{
campos = new Dictionary<string, JValue>();
ObtenerCampos(token);
}
private void ObtenerCampos(JToken jToken)
{
switch (jToken.Type)
{
case JTokenType.Object:
foreach (var child in jToken.Children<JProperty>())
ObtenerCampos(child);
break;
case JTokenType.Array:
foreach (var child in jToken.Children())
ObtenerCampos(child);
break;
case JTokenType.Property:
ObtenerCampos(((JProperty)jToken).Value);
break;
default:
//forma campos:
campos.Add(jToken.Path, (JValue)jToken);
break;
}
}
public Dictionary<string, JValue> GetAllCampos() => campos;
}
// the call:
private Dictionary<string, JValue> obtenerCamposApartirdeJson(string parametroJson)
{
Dictionary<string, JValue> estructuraLista = null;
if (!string.IsNullOrEmpty(parametroJson))
{
var json = JToken.Parse(parametroJson);
var fieldsCollector = new Comun.JsonColeccionCampo(json);
estructuraLista = fieldsCollector.GetAllCampos();
}
return estructuraLista;
}
// I have a list "estructuraLista" or type Dictionary<string, JValue> like this:
filas Count = 11 System.Collections.Generic.Dictionary<string, Newtonsoft.Json.Linq.JValue>
[0] {[[0].nombreId, 1016]} System.Collections.Generic.KeyValuePair<string, Newtonsoft.Json.Linq.JValue>
[1] {[[0].nombre, John]}
[2] {[[0].proyecto[0].proyectoId, 1]}
[3] {[[0].proyecto[0].Nombre, ProyectoEmpleados]}
[4] {[[0].proyecto[1].proyectoId, 20]}
[5] {[[0].proyecto[1].Nombre, ProyectoNominas]}
[6] {[[1].nombreId, 1056]}
[7] {[[1].nombre, Sara]}
[8] {[[1].proyecto[0].proyectoId, 22]}
[9]{[[1].proyecto[0].Nombre, ProyectoContabilidad]}
[10]{[[1].proyecto[1].proyectoId, 20]}
[11]{[[1].proyecto[1].Nombre, ProyectoNominas]}
I need to treat the list Dictionary<string, JValue> and then pass them to an excel file in this way:
NombreId Nombre ProyectoId Nombre
1016 John 1016 ProyectoEmpleados
20 ProyectoNominas
1056 Sara 22 ProyectoContabilidad
20 ProyectoNominas
Any idea?