public static string RESTToJsonConverter(string incoming_data){
string data = "[";
int i = 0;
Debug.Log("incoming_data"+incoming_data);
data += "]";
string JSONToParse = "{\"values\":" + data + "}";
return JSONToParse;
}
Below is my result when I run that code. My Question is how can I access/get all the data without taking "M4qRmfIqhKdy643Ujye" key (auto-generate)?
If using JavaScript, I can use object.values but since I'm using C#, I don't know how to get the data.
{
"-M4qRmfIqhKdy643Ujye": {
"assetName": "avatar",
"id": "-M4qRmfnFya7bC43Ujye",
"imageName": "icon_avatar",
"name": "Bob",
"objName": "Bobby",
"point": "-M4vZRY9vhKs65n5L_Gk",
"versionNumber": "3"
},
"-M4qRmfIqhKdy643Ujye": {
"assetName": "avatar",
"id": "-M4qRmfnFya7bC43Ujye",
"imageName": "icon_avatar",
"name": "Bobfds",
"objName": "Bobbydsf",
"point": "-M4vZRY9vhKs65n5L_Gk",
"versionNumber": "3"
},
"-M4qRmfIqhKdy643Ujye": {
"assetName": "avatar",
"id": "-M4qRmfnFya7bC43Ujye",
"imageName": "icon_avatar",
"name": "Bobfdsa",
"objName": "Bobbyfc",
"point": "-M4vZRY9vhKs65n5L_Gk",
"versionNumber": "3"
}
}
UPDATE
This is one of function in my Downloader Class
IEnumerator DownloadData(string dataPath, Action<string> callback){
Debug.Log("dataPath=>"+dataPath);
var token = LocalData.getAuth();
Auth data = JsonUtility.FromJson<Auth>(token);
var request = new
UnityWebRequest("https://test123.firebaseio.com/"+dataPath+".json?
auth="+data.idToken, "GET");
request.downloadHandler = (DownloadHandler) new
DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.isHttpError || request.isNetworkError)
{
Debug.Log(request.error);
NotificationHelper.showOnePopup("Error \n"+request.error);
callback(null);
}
else
{
//Debug.Log(request.downloadHandler.text);
string json =
FirebaseSetup.RESTToJsonConverter(request.downloadHandler.text);
callback(json);
}
Below is my FirebaseSetup Class
public static string FirebaseToJsonConverter(DataSnapshot snapshot){
string data = "[";
int i = 0;
foreach(DataSnapshot s in snapshot.Children){
data += s.GetRawJsonValue();
i++;
if(i != snapshot.ChildrenCount)
data += ",";
}
data += "]";
string JSONToParse = "{\"values\":" + data + "}";
return JSONToParse;
}
public static string RESTToJsonConverter(string incoming_data)
{
Debug.Log($"incoming_data:/n{incoming_data}");
// remove everything before the SECOND occurrence of '{'
// remove last occurrence of '}'
var startIndex = incoming_data.IndexOf('{', incoming_data.IndexOf('{') + 1);
var endIndex = incoming_data.LastIndexOf('}') - 1;
var json = incoming_data.Substring(startIndex, endIndex - startIndex);
// then remove leading or trailing whitespace
json = json.Trim();
Debug.Log($"json:/n{json}");
var data = JsonUtility.FromJson<string>(json);
return data;
}
After I try #derHugo code, I get new error.
This is my new error
For your specific case I would go the other way round:
The root field name usually doesn't matter so if you remove the trailing } and start the string from the second { you would have
{
"assetName": "avatar",
"id": "-M4qRmfnFya7bC43Ujye",
"imageName": "icon_avatar",
"name": "Bob",
"objName": "Bobby",
"point": "-M4vZRY9vhKs65n5L_Gk",
"versionNumber": "3"
}
which you can simply create a c# class for
[Serializable]
public class Data
{
public string assetName;
public string id;
public string imageName;
public string name;
public string objName;
public string point;
public string versionNumber;
}
and then you could use JsonUtility
public static Data RESTToJsonConverter(string incoming_data)
{
Debug.Log($"incoming_data:/n{incoming_data}");
// remove everything before the SECOND occurrence of '{'
// remove last occurrence of '}'
var startIndex = incoming_data.IndexOf('{', incoming_data.IndexOf('{') + 1);
var endIndex = incoming_data.LastIndexOf('}') - 1;
var json = incoming_data.Substring(startIndex, endIndex - startIndex);
// then remove leading or trailing whitespace
json = json.Trim();
Debug.Log($"json:/n{json}");
var data = JsonUtility.FromJson<Data>(json);
return data;
}
Update
You now updated your question content so now the data comes as a Dictionary of data objects.
In this case you could use Newtonsoft Json.NET which directly supports (de)serialization of Dictionary like e.g.
[Serializable]
public class Data
{
public string assetName;
public string id;
public string imageName;
public string name;
public string objName;
public string point;
public string versionNumber;
}
and then do something like
public static Dictionary<string, Data> RESTToJsonConverter(string incoming_data)
{
Debug.Log($"incoming_data:/n{incoming_data}");
var data = JsonConvert.DeserializeObject<Dictionary<string, Data>(json);
return data;
}
then you can do e.g.
var datas = RESTToJsonConverter(receivedRawData);
foreach(var data in data.Values)
{
Debug.Log(data.id);
}
I suppose, your question is about the deserialization of the JSON with non-unique keys.
If it is, take to look over here: How to deserialize JSON with duplicate property names in the same object
In your case, the solution should contain the following:
declaring your contract:
public class Data
{
public string assetName{get;set;}
public string id{get;set;}
public string imageName{get;set;}
public string name{get;set;}
public string objName{get;set;}
public string point{get;set;}
public string versionNumber{get;set;}
}
your "custom deserializer" :)
public static JToken DeserializeAndCombineDuplicates(JsonTextReader reader)
{
if (reader.TokenType == JsonToken.None)
{
reader.Read();
}
if (reader.TokenType == JsonToken.StartObject)
{
reader.Read();
JObject obj = new JObject();
while (reader.TokenType != JsonToken.EndObject)
{
string propName = (string)reader.Value;
reader.Read();
JToken newValue = DeserializeAndCombineDuplicates(reader);
JToken existingValue = obj[propName];
if (existingValue == null)
{
obj.Add(new JProperty(propName, newValue));
}
else if (existingValue.Type == JTokenType.Array)
{
CombineWithArray((JArray)existingValue, newValue);
}
else // Convert existing non-array property value to an array
{
JProperty prop = (JProperty)existingValue.Parent;
JArray array = new JArray();
prop.Value = array;
array.Add(existingValue);
CombineWithArray(array, newValue);
}
reader.Read();
}
return obj;
}
if (reader.TokenType == JsonToken.StartArray)
{
reader.Read();
JArray array = new JArray();
while (reader.TokenType != JsonToken.EndArray)
{
array.Add(DeserializeAndCombineDuplicates(reader));
reader.Read();
}
return array;
}
return new JValue(reader.Value);
}
private static void CombineWithArray(JArray array, JToken value)
{
if (value.Type == JTokenType.Array)
{
foreach (JToken child in value.Children())
array.Add(child);
}
else
{
array.Add(value);
}
}
some code to get a Dictionary<string, Data[]> as a result type
using (StringReader sr = new StringReader(json))
using (JsonTextReader reader = new JsonTextReader(sr))
{
var parsed = DeserializeAndCombineDuplicates(reader).ToObject<Dictionary<string, Data[]>>();
if(parsed!=null)
{
parsed
.ToList()
.ForEach(x=>Console.WriteLine("\r\nkey={0}\r\nvalues:\r\n{1}"
, x.Key
, string.Join("\r\n", x.Value
.Select(z=>string.Join("\t\t", z.name, z.id, z.objName))
.ToArray())));
} else Console.WriteLine("No way, dude!");
}
The full solution is placed here: https://dotnetfiddle.net/lYBytk
Related
{
"12": {
"_agicId": 2,
"_index_": "",
"_seq": 1
},
"11": {
"_agicId": 1,
"_index_": "",
"_seq": 2
},
"10": {
"_agicId": 0,
"_index_": "",
"_seq": 3
}
}
I get a json string like above, but i don't know "12""11""10", how can i parser this json get _seq & agicId?
var Name = JObject.Parse(r);
int Count = Name.Count;
for (int i = 0; i < Name.Count; i++)
{
// how can i get "11"{"agicId":0}
}
For this create a model class like below:
class Test
{
public int _agicId { get; set; }
public string _index_ { get; set; }
public string _seq { get; set; }
}
And then read the json like below. I have read from file . you can read from string also. In the key you will get 11, 12 etc...and in value you will get the Text class having values for "agicId" etc...
using (StreamReader r = new StreamReader("data.json"))
{
string jsonString = r.ReadToEnd();
JObject jsonObj = JObject.Parse(jsonString);
var k = JsonConvert.DeserializeObject<Dictionary<string, Test>>(jsonString);
/*
A very good suggestion by Jon Skeet. No need of this foreach loop. Instead of criticising he has suggested a better solution.
foreach(var item in jsonObj)
{
string key = item.Key;
var value = JsonConvert.DeserializeObject<Test>(item.Value.ToString());
}*/
}
I am looking for a way to split a JSON string into multiple lines after serialization, inserting a newline after every Nth property.
For example, I have this class:
public class Obj
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public string[] Property3 { get; set; }
public string Property4 { get; set; }
public string Property5 { get; set; }
public string Property6 { get; set; }
public TimeSpan Time { get; set; }
public string Property7 { get; set; }
public string Property8 { get; set; }
public string Property9 { get; set; }
public string Property10 { get; set; }
public string[] Property11 { get; set; }
}
Initialized to something like this:
var root = new Obj
{
Property1 = "value1",
Property2 = "value2",
Property3 = new[] {"test", "test1", "test3"},
Property4 = "value4",
Property5 = "value5",
Property6 = "value6",
Time = TimeSpan.FromSeconds(13),
Property7 = "value7",
Property8 = "value8",
Property9 = "value9",
Property10 = "value10",
Property11 = new string[] {"asdf", "basdf"}
};
When I call JsonConvert.SerializeObject(root), it prints out:
{"Property1":"value1","Property2":"value2","Property3":["test","test1","test3"],"Property4":"value4","Property5":"value5","Property6":"value6","Time":"00:00:13","Property7":"value7","Property8":"value8","Property9":"value9","Property10":"value10","Property11":["asdf","basdf"]}
I would like to include a new line once after every Nth property. Let's say every 3rd property.
I tried something like this:
public static string ReplaceEveryNth(string fullString, string pattern, int n)
{
if (n < 1) { return fullString; }
var index = 1;
return Regex.Replace(fullString, pattern, m =>
{
return (index++ % n == 0) ? m.Value + Environment.NewLine : m.Value;
});
}
and called it like this to match key-value pairs on the JSON string:
var replaced = ReplaceEveryNth(json, "(\".*?\":\".*?\"),", 3);
Now, this works for simple properties. But when I start introducing types like arrays, the Regex becomes more complex.
I am wondering if there is a simpler approach.
I'm not sure if this is exactly what you are looking for, but you could try implementing a custom JsonWriter to insert a newline before every Nth property name (assuming you are using Json.Net):
public class CustomJsonWriter : JsonTextWriter
{
public int N { get; set; }
private int propertyCount = 0;
public CustomJsonWriter(TextWriter textWriter, int n) : base(textWriter)
{
N = n;
}
public override void WritePropertyName(string name, bool escape)
{
if (propertyCount > 0 && propertyCount % N == 0)
WriteWhitespace(Environment.NewLine);
base.WritePropertyName(name, escape);
propertyCount++;
}
}
A helper method will make it easy to use:
public static string SerializeWithCustomFormatting(object obj, int n)
{
using (TextWriter sw = new StringWriter())
using (JsonWriter writer = new CustomJsonWriter(sw, n))
{
JsonSerializer ser = new JsonSerializer();
ser.Serialize(writer, obj);
return sw.ToString();
}
}
Then you can do:
string json = SerializeWithCustomFormatting(root, 3);
With your example it would produce output like this:
{"Property1":"value1","Property2":"value2","Property3":["test","test1","test3"]
,"Property4":"value4","Property5":"value5","Property6":"value6"
,"Time":"00:00:13","Property7":"value7","Property8":"value8"
,"Property9":"value9","Property10":"value10","Property11":["asdf","basdf"]}
Fiddle: https://dotnetfiddle.net/gG8az2
Would having a fully indented json work for you?
var json = JsonConvert.SerializeObject(o, new JsonSerializerSettings
{
Formatting = Formatting.Indented
});
Update
Since fully indented json is not good enough you could try a custom converter.
Result
{"Property1":"value1","Property2":"value2","Property3":["test","test1","test3"]
,"Property4":"value4","Property5":"value5","Property6":"value6"
,"Time":"00:00:13","Property7":"value7","Property8":"value8"
,"Property9":"value9","Property10":"value10","Property11":["asdf","basdf"]
}
Converter
public class CustomLineBreakerConverter : JsonConverter
{
private readonly uint n;
private uint i = 1;
public CustomLineBreakerConverter(uint n) { this.n = n; }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Scaffolding from https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
// Please note this will not work recursively (only the top level will be have the new lines
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
var properties = o.Properties();
writer.WriteStartObject();
foreach( var p in properties)
{
p.WriteTo(writer);
if (i++ % n == 0)
{
writer.WriteWhitespace("\r\n"); // This will write a new line after the property even if no more properties
}
}
writer.WriteEndObject();
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
=> throw new NotImplementedException("This converter is meant only for writing");
public override bool CanConvert(Type objectType) => true;
}
Test code
var o = new
{
Property1 = "value1",
Property2 = "value2",
Property3 = new[] { "test", "test1", "test3" },
Property4 = "value4",
Property5 = "value5",
Property6 = "value6",
Time = TimeSpan.FromSeconds(13),
Property7 = "value7",
Property8 = "value8",
Property9 = "value9",
Property10 = "value10",
Property11 = new string[] { "asdf", "basdf" }
};
var json = JsonConvert.SerializeObject(o, new JsonSerializerSettings
{
Formatting = Formatting.None,
Converters = new List<JsonConverter>() { new CustomLineBreakerConverter(3) }
});
Console.WriteLine(json);
I need help deserialize JSON output to a datatable in C# using Newtsonsoft.json (JSON.NET). I have looked at many examples an diskussions on this and many other forums but i can not figure out how to do it.
JSON sample to deserialize:
[{
"display_name": "Check MWExternal",
"plugin_output": "MWExternal.exe: not running",
"host": {
"name": "WIN2008.arlaplast.local"
} },{
"display_name": "Swap usage",
"plugin_output": "Paging File usage is = 39.19 %",
"host": {
"name": "srvdccz01.arlaplast.local"
}},{
"display_name": "Swap usage",
"plugin_output": "Paging File usage is = 40 %",
"host": {
"name": "srvdccz02.arlaplast.local"
}}]
The response structure always looks the same but can have many blocks
I want this in a table looking like this
Here are my code so far: (Only gives me First two columns in table, not the host.name)
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateList();
}
public class Host
{
public string name { get; set; }
}
public class RootObject
{
public string display_name { get; set; }
public string plugin_output { get; set; }
public Host host { get; set; }
}
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
System.Reflection.PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Defining type of data column gives proper data table
var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, type);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
public void PopulateList()
{
string uri = "https://op5.ateavdc.se/api/filter/query?query=[services]%20state!=0&columns=display_name,plugin_output,host.name";
string _auth = string.Format("{0}:{1}", "USERNAME", "PASSWÒRD");
string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
string _cred = string.Format("{0} {1}", "Basic", _enc);
try
{
dynamic webRequest__1 = (HttpWebRequest)WebRequest.Create(uri);
webRequest__1.Headers.Add("Authorization", _cred);
webRequest__1.ContentType = "application/json; charset=utf-8";
webRequest__1.Method = "GET";
dynamic webResponse = (HttpWebResponse)webRequest__1.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
dynamic reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
TextBox1.Text = s.ToString();
var data = JsonConvert.DeserializeObject<List<RootObject>>(s);
DataTable dt = ToDataTable(data);
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
Response.Write(webResponse.StatusCode);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}}}
Thinking that you know how the nested Json is going to come up, based on the example provided, lets create the class,
public class Host
{
public string name { get; set; }
}
public class RootObject
{
public string display_name { get; set; }
public string plugin_output { get; set; }
[JsonProperty("host")]
public Host h { get; set; }
public string Host { get { return this.h.name;} set {this.h.name = value;}}
}
Now lets do the DeserializeObject using NewtonSoft
string s = "[{\"display_name\": \"Check MWExternal\",\"plugin_output\": \"MWExternal.exe: not running\",\"host\": { \"name\": \"WIN2008.arlaplast.local\"} },{\"display_name\": \"Swap usage\",\"plugin_output\": \"Paging File usage is = 39.19 %\",\"host\": { \"name\": \"srvdccz01.arlaplast.local\"}},{\"display_name\": \"Swap usage\",\"plugin_output\": \"Paging File usage is = 40 %\",\"host\": { \"name\": \"srvdccz02.arlaplast.local\"}}]";
JsonConvert.DeserializeObject<List<RootObject>>(s);
You will get the output as below,
Then if you filter against that using linq,
JsonConvert.DeserializeObject<List<RootObject>>(s).Select(x => new {x.display_name, x.plugin_output, x.Host})
Hope this helps..!
Simplest solution:
var json = File.ReadAllText("data.json");
var arr = JArray.Parse(json);
var data = arr.Select(x => new
{
DisplayName = x.Value<string>("display_name"),
PluginOutput = x.Value<string>("plugin_output"),
Host = x.Value<JToken>("host").Value<string>("name")
})
.ToList();
I'm having a JSON string, it has Key in the form of Camel-case but I need to convert the Key to Pascal-case.
Actual JSON String
string jsonString = "{\"personName\":{\"firstName\":\"Emma\",\"lastName\":\"Watson\"}}";
Expected JSON String : Needs to convert from the above JSON string.
string jsonString = "{\"PersonName\":{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}}";
Kindly assist me how to convert this using C#.
Because I can't sleep.
If you define the following static class of extension methods...
public static class JsonExtensions
{
public static void Capitalize(this JArray jArr)
{
foreach(var x in jArr.Cast<JToken>().ToList())
{
var childObj = x as JObject;
if(childObj != null)
{
childObj.Capitalize();
continue;
}
var childArr = x as JArray;
if(childArr != null)
{
childArr.Capitalize();
continue;
}
}
}
public static void Capitalize(this JObject jObj)
{
foreach(var kvp in jObj.Cast<KeyValuePair<string,JToken>>().ToList())
{
jObj.Remove(kvp.Key);
var newKey = kvp.Key.Capitalize();
var childObj = kvp.Value as JObject;
if(childObj != null)
{
childObj.Capitalize();
jObj.Add(newKey, childObj);
return;
}
var childArr = kvp.Value as JArray;
if(childArr != null)
{
childArr.Capitalize();
jObj.Add(newKey, childArr);
return;
}
jObj.Add(newKey, kvp.Value);
}
}
public static string Capitalize(this string str)
{
if (string.IsNullOrEmpty(str))
{
throw new ArgumentException("empty string");
}
char[] arr = str.ToCharArray();
arr[0] = char.ToUpper(arr[0]);
return new string(arr);
}
}
You can:
void Main()
{
string jsonString =
"{\"personName\":{\"firstName\":\"Emma\",\"lastName\":\"Watson\"}}";
var jObj = JObject.Parse(jsonString);
jObj.Capitalize();
Console.WriteLine(jObj.ToString()); //yay!
}
What is the best way to convert a JSON object into querystrings to append to a GET Url? The POST is straight forward and gets read by my Web API backend.
{Name: 'Mike' } = ?Name=Mike
private static string MakeRequest(HttpWebRequest req, string data)
{
try
{
if (req.Method == Verbs.POST.ToString() || req.Method == Verbs.PUT.ToString() || req.Method == Verbs.DELETE.ToString())
{
var encodedData = Encoding.UTF8.GetBytes(data);
req.ContentLength = encodedData.Length;
req.ContentType = "application/json";
req.GetRequestStream().Write(encodedData, 0, encodedData.Length);
}
using (var response = req.GetResponse() as HttpWebResponse)
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
catch (WebException we)
{
if(we.Response == null)
{
return JsonConvert.SerializeObject(new { Errors = new List<ApiError> { new ApiError(11, "API is currently unavailable") }});
}
using (var response = we.Response as HttpWebResponse)
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
If the json object is flat as in your example, then
string json = #"{
""name"": ""charlie"",
""num"": 123
}";
var jObj = (JObject)JsonConvert.DeserializeObject(json);
var query = String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp=>jp.Name + "=" + HttpUtility.UrlEncode(jp.Value.ToString())));
query would be name=charlie&num=123
I make this code to run in .Net Core:
public static string JsonToQuery(this string jsonQuery)
{
string str = "?";
str += jsonQuery.Replace(":", "=").Replace("{","").
Replace("}", "").Replace(",","&").
Replace("\"", "");
return str;
}
Example:
var _baseURI = "http://www.example.com/";
var endPoint = "myendpoint";
ExampleObjectModel requestModel = new ExampleObjectModel();
var requestModelJson = JsonConvert.SerializeObject(requestModel);
var url = string.Format("{0}{1}{2}", _baseURI, endPoint, requestModelJson.JsonToQuery());
Try this, work all object, in deep
public static class ExtensionMethods
{
public static string GetQueryString(this object obj, string prefix = "")
{
var query = "";
try
{
var vQueryString = (JsonConvert.SerializeObject(obj));
var jObj = (JObject)JsonConvert.DeserializeObject(vQueryString);
query = String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp =>
{
if (jp.Value.Type == JTokenType.Array)
{
var count = 0;
var arrValue = String.Join("&", jp.Value.ToList().Select<JToken, string>(p =>
{
var tmp = JsonConvert.DeserializeObject(p.ToString()).GetQueryString(jp.Name + HttpUtility.UrlEncode("[") + count++ + HttpUtility.UrlEncode("]"));
return tmp;
}));
return arrValue;
}
else
return (prefix.Length > 0 ? prefix + HttpUtility.UrlEncode("[") + jp.Name + HttpUtility.UrlEncode("]") : jp.Name) + "=" + HttpUtility.UrlEncode(jp.Value.ToString());
}
)) ?? "";
}
catch (Exception ex)
{
}
return query;
}
}
To use: SomeObject.GetQueryString();
if your object(Entity) have a Children like this Entity :
public class Parent
{
public Child childs { get; set; } = new Child();
public int PageIndex { get; set; }
public int? PageSize { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
}
Your Can Use This Code For Build Query:
First Convert You Enrity Model To JObject
And Call This Method :
public static string GetQueryString(this JObject jObj)
{
return String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp =>
{
if (jp.Value.Type == JTokenType.Object)
{
var arrValue = String.Join("&",
jObj.Values().Children().Cast<JProperty>()
.Select(jp => jp.Path + "=" + HttpUtility.UrlEncode(jp.Value.ToString())));
return arrValue;
}
else
{
var arrValue = String.Join("&", jp.Name + "=" + HttpUtility.UrlEncode(jp.Value.ToString()));
return arrValue;
}
}
)) ?? "";
}
Your Can Get Like This QueryString :
childs.Id=1&childs.Name="Test"&PageIndex=1&PageSize=1