C# json parse string inside 2nd curly brackets {X{Y}} - c#

I try to parse string inside 2nd curly brackets using C# / json
String looks like this:
{"R27":{"DEVX":0.1346224}}
My aim is read value of DEVX, which is 0.1346224
I've tried:
var joR = JObject.Parse(R);
string R27 = joR["R27"].ToString();
RETURNS : {"DEVX":0.1346224}}
string R27 = joR["DEVX"].ToString();
RETURNS ERROR
Is there way to get directly value "0.1346224" without playing with string?

Yes, absolutely - assuming you know the two names involved, you can just index twice, once to get the object for R27, then once within that object to get the value of DEVX:
using System;
using Newtonsoft.Json.Linq;
public class Test
{
static void Main()
{
string json = "{\"R27\":{\"DEVX\":0.1346224}}";
var obj = JObject.Parse(json);
double devX = (double) obj["R27"]["DEVX"];
Console.WriteLine(devX);
}
}

var joR = JObject.Parse(R);
var R27 = joR["R27"]["DEVX"].ToString();

Related

Better way to converting string [123,234,...] to List<int> and back

Basically, I am trying to convert what appears to be an array of integer values stored in a string type.
[123,234,345,456] // example
Currently, I am doing the following to convert string to List<int> or an int[]:
var intList = "[123,234,345,456]".Replace("[","").Replace("]","").Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).Tolist();
Perform required operations (sort, add, remove) on the list and convert it back to a string:
string.Format("[{0}]", string.Join(",", intList));
But then this got me thinking. The data that I am working with looks like JSON. Surely there must a more direct way of converting the string into an array of integers?
I looked at using JArray.Parse(string) from Newtonsoft.Json.Linq but isn't that just adding an extra layer of complexity as now I am dealing with JArray<JToken> instead of standard int[].
If anyone has a neater solution that doesn't involve adding methods, extensions or libraries I would appreciate if you can share your knowledge.
You are correct - JSON can do this for you:
using System;
using Newtonsoft.Json;
namespace Demo
{
class Program
{
static void Main()
{
string test = "[123,234,345,456]";
var result = JsonConvert.DeserializeObject<int[]>(test);
// This prints "123, 234, 345, 456"
Console.WriteLine(string.Join(", ", result));
string andBackAgain = JsonConvert.SerializeObject(result);
// This prints "[123,234,345,456]"
Console.WriteLine(andBackAgain);
}
}
}
If your intention is to parse numbers with double quotes then
string input = #"[123,234,345,456]";
string pattern = #"\d+";
var result = Regex.Replace(input, pattern, "\"$&\"");
result.Dump();
//["123","234","345","456"]
or to parse whole object inside array braces
string input = #"[123,234,345,456]";
string pattern = #"(\d+\s*,?\s*)+";
var result = Regex.Replace(input, pattern, "\"$&\"");
result.Dump();
//["123,234,345,456"]

How to use string interpolation and verbatim string together to create a JSON string literal?

I'm trying to create a string literal representing an array of JSON objects so I thought of using string interpolation feature as shown in the code below:
public static void MyMethod(string abc, int pqr)
{
string p = $"[{{\"Key\":\"{abc}\",\"Value\": {pqr} }}]";
}
Now I thought of using verbatim string so that I don't have to escape double quotes using backslashes. So I came to know through this answer that verbatim string and string interpolation can be used together. So I changed my code as below:
public static void MyMethod(string abc, int pqr)
{
string p = $#"[{{"Key":"{abc}","Value": {pqr} }}]";
}
But it fails to compile. Can anyone help me if there is anything wrong in my usage or it will not be possible to escape double quotes in such a case using string verbatim feature of C#?
The best way is to use JSON serializers as they have in-built handling related to escape characters and other things. See here.
However, if we want to go through this path only to create the JSON string manually, then it can be solved as follows by changing the inner double quotes to single quotes :
public static string MyMethod(string abc, int pqr)
{
string p = $#"[{{'Key':'{ abc}','Value': {pqr} }}]";
return p;
}
I agree with everyone else that building it from strings is a bad idea.
I also understand that you don't want to include an extra dependency.
Here's a bit of code I wrote previously to convert a Dictionary to a JSON string. It's pretty basic, only accepts string types, and doesn't escape quote marks in any of the names/values, but that can be done fairly easily.
If you're trying to serialize a large JSON string from basic types, this is the way I'd recommend to do it. It'll help you stay sane.
private static string DictToJson(Dictionary<string, string> Dict)
{
var json = new StringBuilder();
foreach (var Key in Dict.Keys)
{
if (json.Length != 0)
json = json.Append(",\n");
json.AppendFormat("\"{0}\" : \"{1}\"", Key, Dict[Key]);
}
return "{" + json.ToString() + "}";
}
you can create dictionary and serialize it to json using Json.NET does this.
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }
you can see here more detail : http://www.newtonsoft.com/json/help/html/SerializingCollections.htm

string being appened to json output

I am trying to use json.net to produce a web service but I am a bit perplexed as to why < string > is showing in the dummy data
[WebMethod]
public string getCustomerInfo(string IVACode)
{
var customerData = _dal.apertureAppstblCustomers.Where(a => a.IVACode == IVACode).ToList();
var jsonstring = JsonConvert.SerializeObject(customerData);
return jsonstring;
}
ie its starting like <string> and ending </string> how do i get it to display CustomerInformationinstead of string is it good practise to be naming the nodes?.
[{"id":"7aee450a-a9a7-4f19-83d3-467a3b8a39c0","IVACode":"IVA002","FirstName":"Peter","LastName":"Carson","AddressLine1":"Waters Edge Belfast","AddressLine2":null,"Town":"Belfast","County":"Down","PostCode":"BT99YXX","Telephone":null,"EmailAddress":"email","isActive":true,"authUserName":null,"authCreatedDate":null,"personalProgressValue":null,"contributionsToDate":null,"totalContributions":null,"totalArrears":50000.00,"totalPaid":null,"isDeleted":false,"deviceId":null,"deviceOs":null}]
You will need to convert the serialized string back to your object and then consume it to show the relevant information.
Example below.
JsonConvert.DeserializeObject(jsonstring)
You shouldn't get that in the serialized string but you can replace those tokens using Replace() string function like
jsonstring = jsonstring.Replace("<string>","").Replace("</string>","");

How to convert or serialized data to Json format in c#?

Am using following code to convert data to Json and return value is:
"{\"BillNo\":18}" . But i want to return value for key and value pair Like: {"BillNo":18}
public String Get()
{
var MaxBillNo = db.Billings.Max(b => b.BillNo.Substring(9, 5));
int i = Int32.Parse(MaxBillNo);
BillNumber billNumber = new BillNumber();
billNumber.BillNo = i;
string json = JsonConvert.SerializeObject(billNumber);
return json;
}
"{\"BillNo\":18}" is valid json string will be parsed in javascript on client side but not {"BillNo":18}
var myJson = "{\"BillNo\":18}";
console.log(JSON.parse(myJson));
Unfortunately it is not possible. It is standard C# string formatting rules.
\" is a double quotation mark. See Escape Sequences: https://msdn.microsoft.com/en-us/library/h21280bw.aspx
It is possible in C# but for that you have to pass a list of objects to serialize method. Here is the sample given below, hope so it will be helpful for you.
SmaccLib smacclib = new SmaccLib();
smaccDate = smacclib.Date_SaveFormat(date);
List<EmployeeAbsents> listEmployeeAbsents = _hrManager.EmployeeAbsentManager.SelectEmployeeAbsentsByDate(smaccDate, rowIndex);
if (listEmployeeAbsents != null && listEmployeeAbsents.Count > 0)
{
return JsonConvert.SerializeObject(listEmployeeAbsents);
}
return string.Empty;
And you result will be something like this.
"[{"EmployeeAbsentID":"81e930bb-a38e-4b85-ba6c-9cbd6e706872","EmployeeCode":"20","EmployeeName":"Bilal","AbsentDate":"11/09/2016","AbsentTypeCode":"10","AbsentTypeName":"Casual","IsDeductable":true,"Remarks":"re","EntryFrom":0,"RowIndex":4,"OperatingUserID":0,"RecordTimeStamp":"2016-02-19T13:20:44.417"}]"

Properly decode a text that contains strings like \u003c or \u00252 in c#

I have a JSon response that contains lots of \u003c or \u00252 or other similar strings inside.
I need a proper function in order to decode these strings into proper characters.
There are various posts about how to deserialize JSON strings. Here shows a nice generic method for deserializing. The code below is taken from there.
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms); // <== Your missing line
return obj;
}
}
Having re-read your post if you are just looking for a way to convert the string to ASCII then check out this post. ORiginal Creadit to #Adam Sills for this code
static string DecodeEncodedNonAsciiCharacters( string value ) {
return Regex.Replace(
value,
#"\\u(?<Value>[a-zA-Z0-9]{4})",
m => {
return ((char) int.Parse( m.Groups["Value"].Value, NumberStyles.HexNumber )).ToString();
} );
}
Note I'm assuming you just have the data part of the string, not an entire JSON fragment - i.e.
string s = #"blah \u003c blah \u00252 blah";
If the above assumption is wrong and you have a full JSON fragment, just use JavaScriptSerializer to get an object from the data.
Annoyingly, HttpUtility has encode but not decode.
You could spoof the string into a full JSON object, though - this seems a bit overkill:
class Dummy
{
public string foo { get; set; }
}
static void Main(string[] args)
{
string s = #"blah \u003c blah \u00252 blah";
string json = #"{""foo"":""" + s + #"""}";
string unencoded = new JavaScriptSerializer().Deserialize<Dummy>(json).foo;
}
I'm not sure but I think you can construct a char directly with the unicode character code:
char c='\003C'; // c|60 '<'

Categories