Skip to content

Instantly share code, notes, and snippets.

@seayxu
Created May 31, 2016 03:44
Show Gist options
  • Save seayxu/bf4f81988489a4d65144b92e1d0224cf to your computer and use it in GitHub Desktop.
Save seayxu/bf4f81988489a4d65144b92e1d0224cf to your computer and use it in GitHub Desktop.
C# foreach json node function by Newtonsoft.Json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string jsonstr =
"{\"timestamp\":\"2016-04-08 11:21:25\",\"apiKey\":\"jdtest\",\"data\":{\"adultQuantity\":3,\"childQuantity\":0,\"babyQuantity\":0,\"segmentList\":[{\"departCityCode\":\"PNZ\",\"arriveCityCode\":\"SHA\",\"departDate\":\"2016-04-19\"}]},\"H\":\"value\",\"c\":null,\"v\":\"\",\"w\":\"null\"}";
Dictionary<string, object> dict = new Dictionary<string, object>();
JObject _jObject = JObject.Parse(jsonstr);
string str = Fun(_jObject);
}
public static string Fun(JObject obj)
{
string result = null;
foreach (var item in obj)
{
if (typeof(JObject) == item.Value.GetType())
{
JObject child = (JObject)item.Value;
string tmp = Fun(child);
result += tmp;
}
else if (typeof(JArray) == item.Value.GetType())
{
JArray _jarray = (JArray)item.Value;
foreach (var jitem in _jarray)
{
JObject jchild = (JObject)jitem;
string tmp = Fun(jchild);
result += tmp;
}
}
else
{
if (!(item.Value != null && item.Value.ToString().Trim().Equals("")))
{
result += string.Format("{0}={1},", item.Key, item.Value);
}
}
}
return result;
}
public static T JsonDeSerializerObj<T>(string json)
{
T t = JsonConvert.DeserializeObject<T>(json);
return t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment