I want to convert this style in C#.I want to add Contacts.How can I do it?
My Json:
[{
"Id": "1",
"Name": "emre",
"Country": "istanbul"
}, {
"Id": "2",
"Name": "semih",
"Country": "siirt"
}]
I want this style:
{
"contacts": [
{ "Id": "1",
"Name": "emre",
"Country": "istanbul"
},
{ "Id": "2",
"Name": "semih",
"Country": "siirt"
}
]
}
My web service:
String resultJSON = "";
JavaScriptSerializer js = new JavaScriptSerializer();
try{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
con.Open();
cmd = new SqlCommand("Select * from City", con);
reader = cmd.ExecuteReader();
dt = new DataTable();
con.Close();
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<String, Object>> tableRows = new List<Dictionary<string, object>>();
Dictionary<String, Object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col].ToString());
}
tableRows.Add(row);
}
resultJSON = serializer.Serialize(tableRows).ToString();
}
catch (Exception ex)
{
resultJSON = ex.Message.ToString();
}
Context.Response.Write(resultJSON);
// return resultJSON;
}
Instead of directly serializing the rows create a data model say class named Contact which has the different properties like Id , Name, country , fill it up from the database and use a library like JSON.net to serialize it .
Something similar should work for your datamodel. Please look the Serializing Collections from JSON.net
Product p1 = new Product
{
Name = "Product 1",
Price = 99.95m,
ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
};
Product p2 = new Product
{
Name = "Product 2",
Price = 12.50m,
ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
};
ProductList productList = new ProductList ();
p.Add(p1);
p.Add(p2);
string json = JsonConvert.SerializeObject(productList , Formatting.Indented);
class ProductList
{
Public List<Product> products{get;set;}
// Add method or other methods you require for your collection
}
Like Ashley John said, it would be smart to create a class representing the data json data structure. If you are lazy, or i doubt how it should look, you can use json2csharp to create the class.
Then use a json serializer of your choice, f.x. JSON.net as mentioned by Ashley J, to serialize the entire enumerable of Contacts at once. If you need the json value to be named 'contacts', you can create a containing class with field for the enumerable of contacts, so that when you serialize the containing class, you get the wanted result
Related
In JavaScript I can easily create an object and assign variables with some very basic notation such as:
const Object = JSON.parse('
{
"something": outsideVariable,
"someArray": [
"hey",
"there"
]
}
');
Is there a simple way to do this with C# that is clean and easy to assign variables too? I experimented a bit with the JsonObject but the code for that looks needlessly messy, for example:
JsonObject jsonPayload = new JsonObject
{
["documentId"] = documentID,
["testMode"] = true,
["signers"] = new JsonArray
{
new JsonObject
{
["label"] = "John Smith",
["contactMethod"] = new JsonArray
{
new JsonObject
{
["type"] = "link"
}
}
}
}
};
I also tried using the literal symbol (#) with a string, but it ends up injecting carriage returns and linefeeds, and inserting variables winds of being a great deal of concatination.
IMHO , the most close you want is this
var jsonPayload = new
{
documentId = 1,
testMode = true,
signers = new object[]
{
new {
label="John Smith",
contactMethod= new object[]
{
new {
type="link"
}
}
}
}
};
and code
var json= System.Text.Json.JsonSerializer
.Serialize(jsonPayload,new JsonSerializerOptions { WriteIndented = true });
//or if you need
var jsonParsed= JsonDocument.Parse(json);
result
{
"documentId": 1,
"testMode": true,
"signers": [
{
"label": "John Smith",
"contactMethod": [
{
"type": "link"
}
]
}
]
}
I am trying to serialize Dictionary to .json file and to deserialize it from the current file.
I have the next code:
string filePath = AppDomain.CurrentDomain.BaseDirectory;
Dictionary<string, int> dict = new Dictionary<string, int>() {
{ "aaa", 1},
{ "bbb", 2},
{ "ccc", 3}
};
This works fine
File.WriteAllText(filePath + "IndexedStrings.json", JsonConvert.SerializeObject(dict, Newtonsoft.Json.Formatting.Indented));
The result is:
{
"aaa": 1,
"bbb": 2,
"ccc": 3
}
But when I use this:
File.WriteAllText(filePath + "IndexedStrings.json", JsonConvert.SerializeObject(dict.OrderByDescending(kvp => kvp.Value), Newtonsoft.Json.Formatting.Indented));
The result is:
[
{
"Key": "ccc",
"Value": 3
},
{
"Key": "bbb",
"Value": 2
},
{
"Key": "aaa",
"Value": 1
}
]
Should I use different way to serialize the Dictionary() or how can I deserialize it?
As others have noted, generally you shouldn't care about the order of your object properties. That's one of the fundamental differences between objects and arrays.
However, if you insist, you can manually construct a JObject from your pre-ordered pairs then serialize it:
var jObj = new JObject();
foreach (var kv in dict.OrderByDescending(x => x.Value))
{
jObj.Add(kv.Key, kv.Value);
}
var result = JsonConvert.SerializeObject(jObj, Newtonsoft.Json.Formatting.Indented);
I have a JSON array and I am adding items. I want to display this JSON in a particular format.
My code:
var array = new List<object>();
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
});
array.Add(new
{
ItemName = itnme,
Price = price,
Quantity = quant,
});
This is what my array looks like. I am adding some items. Right now it produces the following output:
[{"Dealname":"unnideal","Ticketcount":"25","OriginalPrice":"100","Dealsticketcount":"1","dealprice":"200","totalprice":"300},{"ItemName":"popcorn","Price":"100","Quantity":"1"},{"ItemName":"piza","Price":"100","Quantity":"1"}]
But i need my output like this:
[{"Dealname":"unnideal","Ticketcount":"25","OriginalPrice":"100","Dealsticketcount":"1","dealprice":"200","totalprice":"300"},"Offers"[{"ItemName":"popcorn","Price":"100","Quantity":"1"},{"ItemName":"piza","Price":"100","Quantity":"1"}]]
That is, I need an array for offers. How can I make this possible?
Your problem appears to be that your parent object, and child "offer" objects are not related, when Offers needs to be part of the main object.
Try something like this:
var array = new List<object>();
var offers = new List<object>();
offers.Add(new
{
ItemName = itnme,
Price = price,
Quantity = quant,
});
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
Offers = offers
});
Sounds like you just want another property named "Offers"?
var array = new List<object>();
var offers = new[]
{
new {ItemName = itnme, Price = price, Quantity = quant}
...
};
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
Offers = offers // adding Offers as a property here
});
This should produce a JSON like the following:
[
{
"Dealname": "unnideal",
"Ticketcount": "25",
"OriginalPrice": "100",
"Dealsticketcount": "1",
"dealprice": "200",
"totalprice": "300",
"Offers": [
{
"ItemName": "popcorn",
"Price": "100",
"Quantity": "1"
},
{
"ItemName": "piza",
"Price": "100",
"Quantity": "1"
}
]
}
]
I have two DataTable, RCPT_HEADER and RCPT_DETAIL and trying to serialize into json object hierarchy using Json.NET / C#.
I've already tried code
static JArray DataToArray(string connString, string query)
{
JArray jArray = new JArray();
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int fieldcount = reader.FieldCount;
object[] values = new object[fieldcount];
reader.GetValues(values);
JObject jo = new JObject();
for (int index = 0; index < fieldcount; index++)
{
jo.Add(reader.GetName(index).ToString(), values[index].ToString());
}
jArray.Add(jo);
}
reader.Close();
}
}
}
catch (SqlException e)
{
WriteLog("[DataToArray]: " + e.Message);
}
return jArray;
}
and
static void Main(string[] args)
{
try
{
Hashtable config = getSettings(AppPath() + "mware.config");
string connString = config["cs"].ToString();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
JObject jObject = new JObject();
JArray jArray = new JArray();
jObject.Add("RCPT_HEADER", DataToArray(connString, "SELECT * FROM RCPT_HEADER"));
jObject.Add("RCPT_DETAIL", DataToArray(connString, "SELECT * FROM RCPT_DETAIL"));
jObject.WriteTo(jsonWriter);
Console.WriteLine(jObject.ToString());
Console.ReadLine();
}
catch (Exception e)
{
WriteLog("[postJSON]: " + e.Message);
}
}
but I'm gettin output like this:
{
"RCPT_HEADER": [
{
"RECORD_ID": "1",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
}
],
"RCPT_DETAIL": [
{
"RECORD_ID": "1",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"LINK_ID": "1",
"ITEM": "SKU00048700007683",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
},
{
"RECORD_ID": "2",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"LINK_ID": "1",
"ITEM": "SKU00048700007684",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
}
]
}
Actually, I would like it to return the output like this:
{
"RCPT_HEADER": [
{
"RECORD_ID": "1",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM",
"RCPT_DETAIL": [
{
"RECORD_ID": "1",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"LINK_ID": "1",
"ITEM": "SKU00048700007683",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
},
{
"RECORD_ID": "2",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"LINK_ID": "1",
"ITEM": "SKU00048700007684",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
}
]
}
]
}
Any help would be greatly appreciated as this is the first time I have tried to use JSON.NET.
As you are using data tables, it will serialize tables this way as a JSON array of tables.
You can write your own JsonConverter in order to serialize it your way. Here is a good article.
However, in my opinion, there is another good but hacky solution: if you always have the same structure and it is not requiring too much performance, it will be easier to deserialize it again, move this object and serialize it back.
Something like this:
string json = "YOUR_JSON_RESULT";
JObject jsonObject = JObject.Parse(json);
((JObject)jsonObject["RCPT_HEADER"][0])
.Properties()
.Last()
.AddAfterSelf(new JProperty("RCPT_DETAIL", jsonObject["RCPT_DETAIL"]));
jsonObject.Remove("RCPT_DETAIL");
string jsonResult = jsonObject.ToString();
There is another one solution which is elegant and sounds proper. You use data tables but you need it to become serialized like it is not a table by implementing custom serializers or modificators. Probably, you just don't need data tables.
Do not use it if possible - use your own classes instead, so that you can describe any nesting and serialization order:
public class RcptDetail
{
public string RECORD_ID { get; set; }
/* ... */
}
public class RcptHeader
{
public string RECORD_ID { get; set; }
/* ... */
public RcptDetail RCPT_DETAIL { get; set; }
}
I am able to create a flat serialized JSON string pretty easily with c#
My issue is I want to create a nested string like this below
[ {
title: "Yes",
id : "1",
menu: [ {
title: "Maybe",
id : "3",
alert : "No",
menu: [ {
title: "Maybe Not",
id : "8",
alert : "No",
menu: []
} ]
} ]
},
{
title: "No",
id : "2",
menu: []
}]
Any help would be great
Are you using MVC 3? - Do something like:
return Json(myObectWithListProperties, JsonRequestBehavior.AllowGet);
I use this to return complex C# objects that match the structure of the JavaScript objects I want.
e.g.:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
]
}
EDIT: A bit more nesting for fun:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
},
test = new {
a = new {
b = new {
something = "testing",
someOtherThing = new {
aProperty = "1",
another = "2",
theThird = new {
bob = "quiteDeepNesting"
}
}
}
}
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
],
"test": {
"a": {
"b": {
"something": "testing",
"someOtherThing": {
"aProperty": "1",
"another": "2",
"theThird": {
"bob": "quiteDeepNesting"
}
}
}
}
}
}
Try using
using System.Web.Script.Serialization;
//Assumed code to connect to a DB and get data out using a Reader goes here
Object data = new {
a = reader.GetString(field1),
b = reader.GetString(field2),
c = reader.GetString(field3)
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(data);
This is built-in and saves you the work of serializing to JSON yourself!
This example assumes you are getting data from a database using some sort of reader, and it then constructs the object you want to serialize using an anonymous class. Your anonymous class can be as simple or complex as you need it to be and the JavaScriptSerializer will handle transforming it to JSON. This approach is also useful because you can easily control the JSON property names it will create in the JSON.
using System.Web.Script.Serialization;
var strNJson = new
{
to = "hello",
notification = new
{
title = "textTitle",
body = "bodyText"
}
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(strNJson);
{ "to":"hello",
"notification": {
"title":"titleText",
"body":"bodyText"
}
}
You can make use of the ExpandoObject under the System.Dynamic namespace.
Here is a small snippet for achieving your solution:
dynamic parameters = new dynamic[2];
parameters[0] = new ExpandoObject();
parameters[0].title = "Yes";
parameters[0].id = "1";
parameters[0].menu = new dynamic[1];
parameters[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].title = "Maybe";
parameters[0].menu[0].id = "3";
parameters[0].menu[0].alert = "No";
parameters[0].menu[0].menu = new dynamic[1];
parameters[0].menu[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].menu[0].title = "Maybe Not";
parameters[0].menu[0].menu[0].id = "8";
parameters[0].menu[0].menu[0].alert = "No";
parameters[0].menu[0].menu[0].menu = new dynamic[0];
parameters[1] = new ExpandoObject();
parameters[1].title = "No";
parameters[1].id = "2";
parameters[1].menu = new dynamic[0];
string json = JsonConvert.SerializeObject(parameters, Formatting.Indented);
Console.WriteLine(json);
Here is the work in fiddle
Note: There are other ways to achieve this, but I have been using this approach.