I have struggled to finish this task, please if anyone can give me a hint I would be so thankful.
My main task is to get data from database using (FOR JSON AUTO) which is working :)
select filed1, field2, field3 from table FOR JSON AUTO;
And then after connecting to Data base I use the StringBuilder() to build a Json Array of objects which is working :)
var jsonResult = new StringBuilder();
if(!r.HasRows)
{
jsonResult.Append("[]");
}
else
{
while(r.Read())
{
jsonResult.Append(r.GetValue(0).ToString());
}
// JArray array = JArray...
}
After that I am trying to change the value of filed1 for each object inside the Json Array
JArray array = JArray.Parse(jsonResult.ToString());
foreach (JObject obj in array.Children<JObject>())
{
foreach (JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
if(name.ToString() == "field1")
{
Int64 newID = 1234;
value = newID.ToString();
}
}
}
This is working but My BIG QUESTION is how can I get it changed inside the jsonResult?
You simply have to replace the value that you want to update. Since StringBuilder has a .Replace inbuilt method, you can implement that method.
`JArray arr = JArray.Parse(jsonResult.ToString());
foreach (JObject obj in arr.Children<JObject>())
{
foreach(JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
if (name.ToString().Equals("field1")) //good practice
{
Int64 newID = 1234;
jsonResult.Replace(value, newID.ToString());//replacing old value with new value and directly updates jsonResult
}
//not necesssary, explanation is given below
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonResult.ToString());
result = JsonSerializer.Serialize(jsonElement, options);
}
}`
And for better formatting, I used JsonSerializer so that your output will look like json object rather than whole string without any lines.
` var options = new JsonSerializerOptions()
{
WriteIndented = true
};
var result = ""
while loop{
jsonResult.Append(r.GetValue(0).ToString());
(Above code)
}
`
Related
My JSON File
{"data":
[
{"id":"1","user_code":"C016482","name":"CART 1","details":"[{\"Id\":15476,\"Name2\":\"AQUAFRESHIG TEETH (6+)\",\"SalesPriceVM\":250,\"DiscountPercentVM\":0,\"product_quantity\":3,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=15476\"},{\"Id\":22514,\"Name2\":\"BABE ANTI OILY DANDRUFF SHAMPOO 250 ML\",\"SalesPriceVM\":1800,\"DiscountPercentVM\":0,\"product_quantity\":1,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=22514\"},{\"Id\":19886,\"Name2\":\"ALOE VERA GEL\",\"SalesPriceVM\":1674,\"DiscountPercentVM\":0,\"product_quantity\":1,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=19886\"}]","created_at":"2020-05-20 11:52:49","updated_at":"2020-05-20 11:52:49"},
{"id":"2","user_code":"C020552","name":"CART1","details":"[{\"Id\":15480,\"Name2\":\"LISTERINE MOUTHWASH ORIGINAL 500 ML\",\"SalesPriceVM\":460,\"DiscountPercentVM\":0,\"product_quantity\":1,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=15480\"},{\"Id\":20572,\"Name2\":\"SAVLON ACTIVE HAND WASH RF 1000ML\",\"SalesPriceVM\":230,\"DiscountPercentVM\":0,\"product_quantity\":1,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=20572\"},{\"Id\":25899,\"Name2\":\"HANDISANITTIZER 200ML SOLUTION\",\"SalesPriceVM\":100,\"DiscountPercentVM\":0,\"product_quantity\":2,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=25899\"}]","created_at":"2020-05-21 01:43:10","updated_at":"2020-05-21 01:43:10"},
{"id":"3","user_code":"C020557","name":"PR 1","details":"[{\"Id\":13319,\"Name2\":\"EXIUM CAPS 20\",\"SalesPriceVM\":8.5,\"DiscountPercentVM\":0,\"product_quantity\":10,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=13319\"},{\"Id\":16432,\"Name2\":\"DOMIDON 10MG TAB\",\"SalesPriceVM\":2,\"DiscountPercentVM\":0,\"product_quantity\":10,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=16432\"},{\"Id\":19480,\"Name2\":\"ALOCAP SOFT CAP\",\"SalesPriceVM\":6,\"DiscountPercentVM\":0,\"product_quantity\":10,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=19480\"},{\"Id\":23223,\"Name2\":\"CYNTA 100MG TAB.\",\"SalesPriceVM\":25,\"DiscountPercentVM\":0,\"product_quantity\":40,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=23223\"},{\"Id\":2063,\"Name2\":\"MARLOX PLUS-200 ML-SUSPENSION\",\"SalesPriceVM\":110,\"DiscountPercentVM\":0,\"product_quantity\":1,\"Image_Url\":\"http:\\\/\\\/182.160.118.235:8099\\\/api\\\/ImageFile\\\/GetImage?enumEntityType=2&entityId=2063\"}]","created_at":"2020-05-21 07:30:29","updated_at":"2020-05-21 07:30:29"},
]
}
I am trying to read "details". In details, there are three objects I am trying to read Id,product_quantity of each object and insert them into the db table.
MY Code
public void PostSaveCartItemData()
{
var contents = File.ReadAllText("saved_carts.json");
dynamic jsonResponse = JsonConvert.DeserializeObject(contents);
int i = 0;
using (MainDataContext ctx = new MainDataContext())
{
List<SavedCartItem> list = new List<SavedCartItem>();
foreach (var item in jsonResponse.data)
{
var productId = item.details[i].Id;
var qty = item.details[i].product_quantity;
i++;
SavedCartItem entity = new SavedCartItem()
{
ProductId = productId,
Qty = qty ,
};
list.Add(entity);
}
ctx.SavedCartItems.AddRange(list);
ctx.SaveChanges();
}
}
Your kind help will be highly appreciated.
The details property is JSON encoded as a string, you need to further deserialise that value if you want to use it. Also, you should avoid using dynamic, there's no need. For example:
var jsonResponse = JObject.Parse(Json);
foreach (var item in jsonResponse["data"])
{
var detailsJson = item["details"];
var details = JArray.Parse(detailsJson.ToString());
foreach(var detail in details)
{
var productId = detail["Id"];
var qty = detail["product_quantity"];
Console.WriteLine(productId);
Console.WriteLine(qty);
}
}
This is my Json Array
[
{
"gregdate": "06-03-2019",
"maldate": "22-07-1194",
"gregmonth": "March",
"selected_status": "1"
},
{
"gregdate": "04-05-2019",
"maldate": "21-09-1194",
"gregmonth": "May",
"selected_status": "1"
},
{
"gregdate": "03-06-2019",
"maldate": "20-10-1194",
"gregmonth": "June",
"selected_status": "1"
}
]
In this JSON Array, I want to change 2nd JSON Object "selected_status" value "1" to "0" without changing the position of the JSON Object.
You need to first convert you object array to JArray and then change its second object property from 1 to 0 like
string json = "You json here"; //Load your json
JArray jArray = JArray.Parse(json); //Parse it to JArray
var jObjects = jArray.ToObject<List<JObject>>(); //Get list of objects inside array
foreach (var obj in jObjects) //Loop through on a list
{
if (jObjects.IndexOf(obj) == 1) //Get 2nd object from array
{
foreach (var prop in obj.Properties()) //List 2nd objects properties
{
if (prop.Name == "selected_status") //Get desired property
obj["selected_status"] = 0; //Change its value
}
}
}
JArray outputArray = JArray.FromObject(jObjects); //Output array
Alternative:
As suggested by Brian Rogers you can directly query your JArray to replace its specific property value like,
string json = "You json here"; //Load your json
JArray jArray = JArray.Parse(json); //Parse it to JArray
jArray[1]["selected_status"] = "0"; //Querying your array to get property of 2nd object
string outputJson = jArray.ToString(); //Output json
Output: (from debugger)
This question helped me figure a couple things out - so here is what I came up with. I'm guessing that the json is a sample and what is desired is changing the status for a specific date, rather than just the second element. At least that's what I've been looking for. This is more dynamic and you don't have to worry about the position of the element.
string newJson = "";
if (SwitchStatus(jsonString, "04-05-2019", "0", out newJson))
{
Console.Write(newJson);
}
else
{
Console.WriteLine("Date Not Found");
}
Console.ReadLine();
static bool SwitchStatus(string jsonString, string searchBy, string switchTo, out string output)
{
dynamic jsonObj = JsonConvert.DeserializeObject(jsonString);
JToken status = jsonObj.SelectToken($"$..[?(#.gregdate == '{searchBy}')].selected_status");
if (status != null)
{
status.Replace(switchTo);
output = JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
}
else
{
output = jsonString;
}
return status != null;
}
I am trying to parse JSON string in C# solution, but I can't get the internal/nested arrays which start with : ",[["bd felek",0],["bdm",0],["bd",0],["bdz",
["bd",[["bd felek",0],["bdm",0],["bd",0],["bdz",0,[131]],["bd fleke",0],["bd felek dfdf",0],["bdz dance practice",0,[3]],["bdz twice live",0,[131]],["bdo",0,[131]],["bd mawlaya",0]],{"a":"Uwt304b6at0ZtuU8mv8D5AyWS8wg6AQJQbYlPPS8knOVvcG","e":"1","j":"6l","k":1,"q":"ZQXxB0vG-GaPEF2RNib3gbVRXt0"}]
var jsonser = new JavaScriptSerializer();
var obj = jsonser.Deserialize<dynamic>(SourceCodeTxt.Text);
foreach (var x in obj)
{
// MessageBox.Show(x);
String strvalue = x["value"];
}
}
Your code should be looking at the second index (1) of the deserialized object:
foreach (var x in obj[1])
{
var value1 = x[0]; // bd felek
var value2 = x[1]; // 0
}
You want to use JSON.NET to better handle JSON. then you can simply do the following:
using Newtonsoft.Json.Linq;
...
JToken obj = JToken.Parse(/* Your JSON string goes in here */);
foreach (var x in obj[1])
{
var value1 = x[0]; // bd felek
var value2 = x[1]; // 0
...
}
I have code that gets data from JSON:
dynamic myJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(sourceString);
foreach (var item in myJSON["data"]["results"])
{ ... }
Now, I'd like to make this part myJSON["data"]["results"] for versatile, ideally by passing in a variable such as:
dynamic myJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(sourceString);
var variableResults = ((Newtonsoft.Json.Linq.JArray) string.Format("myJSON[\"{0}\"][\"{1}\"]", myData, myResults);
foreach (var item in variableResults)
{ ... }
I've tried different conversions, and looked here, but no question comes close, and the conversions always comes out string, not a JArray. Any ideas?
You can use JObject to parse it:
var json = "{asd: {qwe: [1,2,3,4]}}";
var obj = JObject.Parse(json);
// just plug in your variables here
var myData = "asd";
var myResult = "qwe";
var path = $"{myData}.{myResult}";
foreach (var item in obj.SelectToken(path).ToObject<int[]>())
{
// ...
}
My solution ended up being:
// User would use a textbox with space separated values like "data results"
var parameterList = textBox1.Text.Trim().Replace(" ", ".");
var jsonObject = JObject.Parse(sourceString);
var jsonList = jsonObject.SelectToken(parameterList);
if (jsonList == null) { ... }
foreach (var item in jsonList)
{ ... }
I have below json in string as parameter to a WebMethod.
How can I deserialize in such a way that value comes in Key value pair.
Json String Parameter:
["Ref No,0","Date,0","Amt,0","Sender Name,0","Sender Add,0","Beneficiary Name,0","Beneficiary Add,0","Phone,0","Secret Code,0","Secret Ans,0","Preferred Id,0"]
WebMethod:
[System.Web.Services.WebMethod]
public static string SaveMappings(string mappingData)
{
//string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//object obj;
//var data = serializer.Deserialize(mappingData,);
var data = mappingData.ToArray();
if (data != null)
{
}
var d2 = mappingData.Split(',');
if (d2!=null)
{
}
return mappingData;
}
If you need to work with JSON data then use Newtonsoft.JSON library.
Convert the object to an array of strings and then split every line.
With this approach you can be sure that the given string is actually an JSON array and it is correct.
var str = "[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]";
string[] objs = JsonConvert.DeserializeObject<string[]>(str);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var obj in objs)
{
var keyValue = obj.Split(',');
dic.Add(keyValue[0], keyValue[1]);
}
foreach (var record in dic)
{
Console.WriteLine("{0} => {1}", record.Key, record.Value);
}
Or this one using LINQ. It looks better and it can be written faster. However, it is less optimal (two calls of Split instead of one).
public Dictionary<string, string> FromJsonArray(string jsonArray)
{
return JsonConvert.DeserializeObject<string[]>(jsonArray)
.ToDictionary(obj => obj.Split(',')[0], obj => obj.Split(',')[1]);
}
// ...
var str = "[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]";
foreach (var record in FromJsonArray(str))
{
Console.WriteLine("{0} => {1}", record.Key, record.Value);
}
why don't you just change every ',' in the string array to ':' then pass it to the method, from what you wrote in the question, this should work