{
"FirstName" :"Kaustubh",
"LastName" :" Sawant ",
"StartTime" :"01:00:00"
}
I want to get printed
First Name: Kaustubh
Last Name: Sawant
Start time : 01:00:00
This is the demo code written the actual object retrieves more values.
Actual code :
String JsonValue=JsonConvert.SerializsObject(object);
also used Formatting.Indented and tried
Regex.Replace(JsonValue,#"\{},"","").Trim();
and then wrote into file using StreamWriter.
I think you are attacking this from the wrong angle, if this is truly json, you are best to deserialize it using something like json.net, and then building the string up out of the properties.
However, because you insist on doing it via replacement, you can make use of regex
var result = Regex.Replace(input, #"[,{}\"")]", "").Trim();
Console.WriteLine(result);
Output
FirstName :Kaustubh
LastName : Sawant
StartTime :01:00:00
Full Demo Here
Considering json is a string variable containing your input:
var json = #"
{
""FirstName"" :""Kaustubh"",
""LastName"" :"" Sawant "",
""StartTime"" :""01:00:00""
}";
Simple solution relying on standard library:
Console.WriteLine(json.Replace("{", "").Replace("}", "").Replace("\"","").Replace(",", "").Trim());
A solution using Newtonsoft.Json framework for deserializing json string:
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
foreach (var entry in dict)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
Related
I have a HttpContext.Response function which returns this json response:
{
"[2-1] STORE[STORE_NBR]": 5026,
"[2-1] STORE[STATE_PROV_CD]": "AR"
}
Now, I just want the Keys to be returned and not the value as:
{
[2-1] STORE[STORE_NBR],
[2-1] STORE[STATE_PROV_CD]
}
I tried commenting [1] and [2] but that result in an exception as value is expected. How can this outcome be achieved?
The Json response (as noted in a comment) can be easily deserialized to a Dictionary where both the Key and the Value of the KeyValuePair are strings. Here is how you could do that:
using System.Linq;
using Newtonsoft.Json; // Can be installed as a NuGet package
then
var dictionary =
JsonConvert.DeserializeObject<Dictionary<string,string>>(source);
Once you have the dictionary object, you can use Linq to extract just the Keys that you want and turn them into a list.
List<string> keys =
dictionary.Select(keyValuePair => keyValuePair.Key).ToList();
where
const string source =
#"{
""[2 - 1] STORE[STORE_NBR]"": 5026,
""[2-1] STORE[STATE_PROV_CD]"": ""AR""
}";
These lines of code format the output you specified:
Console.WriteLine(
"Here are the keys:");
Console.WriteLine(
$"{{{Environment.NewLine}{string.Join("," + Environment.NewLine, keys)}{Environment.NewLine}}}");
I am able to read the json file and store it in a JObject variable. I need to check for null values and ignore any segment that has null values. I was thinking of looping through the JObject but I don't know how i can access every segment/ key in the json below.
I think we can loop like this based on another question i saw on here:
foreach (var x in example) //example is the JObject in which json file is stored
{
string name = x.Key;
JToken value = x.Value;
}
But my json doesnt have keys. How do i go in every segment and check if name, description values are not null?
My json is :
{
"lorem ipsum Segment Groups":[
{
"name":"lorem ipsum",
"description":"lorem ipsum",
"segments":[
"Not Enrolled",
"Started Enrollment – Zipcode Lookup",
"Started Enrollment – Passed Flow Step 1",
"Started Enrollment – Passed Flow Step 2"
]
},
{
"name":"lorem ipsum",
"description":"Status Description",
"segments":[
"Moving in next 30 days",
"Moving in next 90 days",
"Not Moving"
]
},
{
"name":"lorem ipsum",
"description":"Interest description",
"segments":[
"Interested - Lots of Time Reading Many Pages",
"Interested - Lots of Time Comparing Products/Prices"
]
}
]
}
Thanks
Here is an example of how to loop through your JSON:
JObject obj = JObject.Parse(json);
JArray segmentGroups = (JArray)obj.Properties().FirstOrDefault()?.Value;
if (segmentGroups != null)
{
foreach (JObject group in segmentGroups.Children<JObject>())
{
string name = (string)group["name"];
string desc = (string)group["description"];
string[] segments = group["segments"]?.ToObject<string[]>();
Console.WriteLine("name: " + (name ?? "(null)"));
Console.WriteLine("description: " + (desc ?? "(null)"));
Console.WriteLine("segments: " + (segments != null ? "\n " + string.Join("\n ", segments) : "(null)"));
Console.WriteLine();
}
}
Fiddle: https://dotnetfiddle.net/kOJzaZ
By knowing the JSON structure, you can use various types with name formatted as JXxx to read the values you want. However here there is one convenient way of selecting the tokens you want by using a json path. That way you can conveniently target the desired set of tokens and continue processing. I'm not so sure about the performance hit with that approach but you may take its trade-off (and if performance does matter, just try benchmarking it first).
The code can be simple like this:
//suppose your example is the loaded JObject
foreach (var group in example.SelectTokens("['lorem ipsum Segment Groups'][*]"))
{
var name = group["name"].Value<string>();
var desc = group["description"].Value<string>();
//check if they are null here ...
}
Note the way we escape keys or paths containing spaces by wrapping it inside ['']. If your key does not need to be escaped, you can use it directly in the path.
The object has 139 fields; the string initializer may have some or all of these fields. It is formatted like this: "FirstName":"Bart","LastName":"Simpson","Company":"Fat Tony's","Address":"55 Maple Drive" etc. I could just look for the fields like this:
if (initializerString.contains("FirstName:")
FirstName="get the next series of chars until the ", or end of string
and so forth. But is there a more compact way to do this?
Seeing as your format is incredibly similar to JSON (except for the lack of braces, actually), as people commented you'll fare better by using JSON.NET.
If you have complete control over this string, just transform it into a json and deserialize it:
JsonConvert.DeserializeObject<YourClass>(yourString);
It will automatically set the correct properties while deserializing your data.
In case you don't have control of this format, and you need to parse it anyway, just put up the braces and you're good:
JsonConvert.DeserializeObject<YourClass>("{" + yourString + "}");
And if you don't have a specific class for this, you can also replace YourClass for a Dictionary<string,object>
You'll find this library as Newtonsoft.Json, and I believe it's the most popular library for dealing with JSON data.
I've made a working example so you can see it in action (note that I kept your string format, but please try to use straight json):
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public class Information
{
public string FirstName{get;set;}
public string LastName{get;set;}
public string Company{get;set;}
public string Address{get;set;}
}
public static void Main()
{
string myObject = "\"FirstName\":\"Bart\",\"LastName\":\"Simpson\",\"Company\":\"Fat Tony's\",\"Address\":\"55 Maple Drive\"";
var converted = JsonConvert.DeserializeObject<Dictionary<string, object>>("{"+myObject+"}");
var converted2 = JsonConvert.DeserializeObject<Information>("{"+myObject+"}");
Console.WriteLine(String.Join("\n", converted.Select(c=> c.Key + ": " + c.Value)));
Console.WriteLine(converted2.FirstName);
}
}
And here's a bonus fiddle:
https://dotnetfiddle.net/fudUYZ
Using regex you could do:
string firstName = Regex.Match(yourstring,#"(?<=""FirstName"":"").*?(?="")").Value;
However this really looks like a json string and there are easier ways to get your data.
You could create a Dictionary<string,object> dict in which there is the name of the property and the property.
You can then split the string,
//Remove the "
initializerString = initializerString.Replace('"', '');
//Split by ,
var tmp = initializerString.Split(",");
//Foreach pair key/value split by :
foreach( var x in tmp){
var tmp2=x.Split(":");
//Assign the value to the property in the Dictionary
dict[tmp2[0]]=tmp2[1];
}
Warning. Since I don't actually know what you're using this code for, this is more of a general idea than working code.
If I have a json string, with one of its property values having a double quote in it, I am not able to parse it.
For example, if my object is { "Name" : "Six \" Pipe" } then the following gives me an error - Unexpected token P.
var str = '{ "Name" : "Six \" Pipe" }';
JSON.parse(str); //error
$.parseJSON(str); //error
The string is formed in a razor view as follows -
var str = new JavaScriptSerializer().Serialize(obj);
And then in JavaScript I am doing
var obj = JSON.parse('#(Html.Raw(str))');
How can I parse such strings?
You should escape the backslashes since in JS it will only \" will be converted to " and will make the JSON incorrect. The blackslash is discarded by javascript.
so the correct string would be-
var str = '{ "Name" : "Six \\" Pipe" }';
JSON.parse(str); //works
Edit:
So, if you want to create a literal backslash in JS, you have to escape it. You can do this while creating this string and double-escaping the key's value. One way to tackle this could be -
To html encode the strings (key values) just like: " instead of \" etc. This seems straight forward to me with .Net. I'm not sure but HttpServerUtility.HtmlEncode could help. Then on the javascript side you could be able to parse straight away- fiddle
I encountered same issue. After spending a lot of time trying to deal with that quotes I came to this solution
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var obj = new {name = "\"Name1\""};
var objJson = serializer.Serialize(obj);
}
<script>
var jsObject = #Html.Raw(objJson);
</script>
I use json as js object without any parsing, html result will be like
<script>
var jsObject = {"name":"\"Name1\""} ;
</script>
which is correct JavaScript. Hope it will be helpfull for somebody
so I'm fairly new to programming but am looking to go much deeper with it. I recently started to get involved in a project to create a WinForm program for a website that uses an API system in JSON.
I've never used an API before so I'm not quite sure how it works but after looking at it for a few minutes I seem to have the gist of it. What I don't get is how exactly parsing JSON in C# works.
I found
this link after a little google searching. And I got it working (somewhat) with this code.
static void Main(string[] args)
{
WebClient c = new WebClient();
var vLogin = c.DownloadString("https://www.openraid.us/index.php/api/login/username/password");
//Returns string
//{"status":1,"error":null,"token":"250-1336515541-c48d354d96e06d488d1a2530071ef07c9532da26"}
//Token = random, no decisive length*/
JObject o = JObject.Parse(vLogin);
Console.WriteLine("Login Status: " + o["status"]);
String sToken = "" + o["token"];
Console.WriteLine(sToken);
Console.WriteLine("");
//Breaks after this
var myRaids = c.DownloadString("https://www.openraid.us/index.php/api/myraids/"+sToken);
JObject r = JObject.Parse(myRaids); //error occurs here
String sEventId = "" + r["event_id"];
Console.WriteLine("Event ID: " + sEventId);
Console.ReadLine();
}
So to me it looks like I have parsing 1 page done and handled, but when I move onto the second I get this error.
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
So I guess my question is, how do I parse more than 1 page or call of JSON and what would be the easiest way to break up each section of the JSON object (Such as status, error, and token, into C# strings?
Did you try to JArray instead? Depending on what kind of object you are trying to return
WebClient client = new WebClient();
var data = client.DownloadString("");
var jArray = JArray.Parse(data);
JSON requires brackets for arrays and commas between multiple objects.
This is per the JSON standard. I also recommend using JSON.net via NuGet instead of the native JSON parser unless it is overkill and you cannot have the extra bloat.
For example, your parsing a file with two seperate JSON objects - the following does not work per the JSON standard (lacks a comma between the 2 objects and the two objects are not encapsulated by brackets):
{"status":1,"error":null}
{"status":2,"error":null}
The following 3 JSON objects parsed from a file does work (has brackets for multiple objects and commas between objects):
[{"glossary": {"title": "fun glossary","SeeAlso": ["GML", "XML"]},
{"glossary": {"title": "grey glossary","SeeAlso": ["GML", "XML"]},
{"glossary": {"title": "blue glossary","SeeAlso": ["GML", "XML"]}]
You can cut every JSON object(Array) into more object using for loops
the C# API is System.Json
var jsonArray = JsonArray.Parse(st);//st is the string which contain the JSON objects
foreach (var item in jsonArray) {
JsonObject ob = new JsonObject(item);
foreach (var t in ob.Values) {
JsonObject oo = new JsonObject(t);
foreach (var x in oo) {
textBox1.AppendText(x.Key + “ : ” + x.Value + “\n”);
}
}
}