Using Newtonsoft.Json to iterate through multiple records - c#

I'm looking for an answer in either C# or VB.net.
I'm getting a string like this:
{"1":{"pump":1,"name":"Pump 1","type":"VS","time":"2:10 PM","run":10,"mode":0,"drivestate":0,"watts":1656,"rpm":2850,"gpm":0,"ppc":0,"err":0,"timer":1,"duration":"durationnotset","currentrunning":{"mode":"off","value":0,"remainingduration":-1},"externalProgram":{"1":-1,"2":-1,"3":-1,"4":-1},"remotecontrol":1,"power":1,"friendlyName":"Pump 1"},"2":{"pump":2,"name":"Pump 2","type":"None","time":"timenotset","run":"runnotset","mode":"modenotset","drivestate":"drivestatenotset","watts":"wattsnotset","rpm":"rpmnotset","gpm":"gpmnotset","ppc":"ppcnotset","err":"errnotset","timer":"timernotset","duration":"durationnotset","currentrunning":{"mode":"off","value":0,"remainingduration":-1},"externalProgram":{"1":-1,"2":-1,"3":-1,"4":-1},"remotecontrol":"remotecontrolnotset","power":"powernotset","friendlyName":"Pump 2"}}
So, just two records. I just need to pull "name", "watts" and "rpm" from each. I don't need to store the entire record in an array or list as I'll just dispose of row anyway.
How can I do this?

You can use Newtonsoft.Json to do this, just find it in on Nuget.
You COULD use it like this, though it's a little dirty...
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText("TextFile1.txt");
JObject jsonObject= (JsonConvert.DeserializeObject(json) as JObject);
string name = jsonObject.Value<JObject>("1").Value<string>("name");
}
}
}
I tested it with your json string in the TextFile1, and it works well. You'd be better off making a custom type for it to deserialise into.
The key parts are the JsonConvert.DeserializeObject(json) which converts the json string into CLR objects, namely a JObject. Then there's the .Value<JObject>("1") bit, which is just using the newtonsoft api.
p.s. I notice you've got a json.net tag on there, their website pretty much says it: https://www.newtonsoft.com/json

Related

Extract data from Json with json.net

so I have a JSON text and I need to Extract Value of some fields from it
{"data":{"shortcode":{"id":"id123","shortcode":"alpha1","by":{"page_info":{"has_next_page":true,"cursor":"sometext=="},"edges":[{"node":{"id":"id1234","username":"admin123","full_name":"admin name",}},{"node":{"id":"id4321","username":"user123","full_name":"user ",}}]}}},"status":"ok"}
now I need the value of every single "username" field and "cursor" from it
I'm new to this topic and I appreciate any kind of help
You could install Newtonsoft.Json, as a Nuget package, if you don't already have it installed in your project. Then use JsonConvert.DeserializeObject() method to parse it into a dynamic object type, using which you can access all its fields/properties.
Code would look something like this-
Add referenceto Newtonsoft.Json
using Newtonsoft.Json;
DeserializeObject method to parse a string into dynamic type (dynamic can be used instead of var)
var obj = JsonConvert.DeserializeObject<dynamic>(text);
For cursor field mentioned in your example
Console.WriteLine(obj.data.shortcode.by.page_info.cursor);
Iterate for each username mentioned your example
foreach (var edge in obj.data.shortcode.by.edges)
{
Console.WriteLine(edge.node.id);
}
NOTE- Because you are using a dynamic type, you will have to be sure that you check for null values to avoid any "NullRefereneException".
Well you can make a new class that match the structure of your json then deserialize the json into that class.

JSON deserialization without using classes? (webservice client)

I am trying to get around that C# prefers to have classes generated (I know they are easy to generate, but currently my format and parameters are changing a lot due to development in both client and server end).
Example of what I most often find when I try to find out to deserialize is that you first have to know the exact structure - then build a class - and then you can refer to it later on (it's fine, but it's just not what I would like to do):
Json format 1:
[{"FirstName":"Bob","LastName":"Johnson"},{"FirstName":"Dan","LastName":"Rather"}]
public class People
{
public string FirstName { get; set; }
public string LastName { get; set;}
}
public List<People> peopleList;
. . . // (same as first example)
//Change the deserialize code to type <List<Class>>
peopleList = deserial.Deserialize<List<People>>(response);
That of course is easy as long as the reply doesn't change format, if for example the reply changes to a nested field :
Json format 2:
[{"FirstName":"Bob","LastName":"Johnson"},{"data":{"nestedfield1"
:"ewr"} }]
I would of course have to change the class to represent that, but at the moment we are moving back and forth in formats and I would somehow like if there was a way where I could try to access json elements directly in the string?
For example, like I can do in Python:
mystring1 = reply ["firstName"] mystring2 = reply ["data"]["nestedfield1"]
Is there any way to achieve this in C#? It would speed up development rapidly if there was a way of accessing it without first referencing the output in the code to then once again reference the class variable that was created when referencing it.
And note it's for rapid development, not necessarily for the final implementation where I can see advantages by doing the class approach.
Another way of asking was maybe can it serialize taking any format (as long as its JSON) and dynamically build up a struct where I can access it with named keys and not as class variables?
to deserialize json without using classes you can use using Newtonsoft.Json
here's the code:
using System;
using Newtonsoft.Json;
using System.Text;
public class Program
{
public static void Main()
{
var myJSONString = "[{\"FirstName\":\"Bob\",\"LastName\":\"Johnson\"},{\"FirstName\":\"Dan\",\"LastName\":\"Rather\"}]";
dynamic obj = JsonConvert.DeserializeObject<dynamic>(myJSONString);
Console.WriteLine(obj[0].FirstName);
}
}
The obj will perform the same way you use when generating classes,
it can take any json string and deserialize into dynamic object regardless of structure of the json. Keep in mind that you won't get VS intellisense support.
UPDATE
Here's fiddle:
https://dotnetfiddle.net/xeLDpK

C# Store values in static dictionary

I have this code , and i want to store values of parameters left, top in static dictionary. and after storing this values i want to access them in Jquery.Thanks For your Help.
my code
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.MoveShape
{
public class MoveShapeHub : Hub
{
public void calculate(string left, string top)
{
Clients.Others.updateshape(left, top);
}
}
}
jQuery operates client-side, so you can't talk to it directly. You have two options, then:
request the value via http (perhaps using SignalR as a messaging layer, since you are referencing that)
serialize the dictionary as JSON into the request
Fortunately, the latter is fairly trivial for most common types - here using Json.NET:
var data = new Dictionary<string, object>
{
{"foo", 123},
{"bar", "abc"},
{"blap", true}
};
var json = JsonConvert.SerializeObject(data);
which gives us the JSON:
{"foo":123,"bar":"abc","blap":true}
If you assign that into a variable in the <script>, then values can be referenced either as obj.bar or as obj['bar']. However: keep in mind that all values will be serialized if you do this - you may want to be more restrictive in terms of tracking which the client actually cares about (or should be allowed to know about).
Important point, though: if your "static dictionary" is actually a static dictionary, then please consider very carefully the impact of multiple users. static is a really good way to write a web-site that only scales to a single user.

Parse JSON String to JSON Object in C#.NET

I have a JSON String returned by my SOAP web service in .NET. It is as follows:
{
"checkrecord":
[
{
"rollno":"abc2",
"percentage":40,
"attended":12,
"missed":34
}
],
"Table1":[]
}
Now I want to parse this string to a JSON Object. I also read this where they have used this line of code:
JObject jsonObj = JObject.Parse(json);
So can I do the same by replacing "json" with my string name. Also do I need to reference any other dll except the NewtonSoft.dll ?
BTW, Here is the full webservice code
use new JavaScriptSerializer().Deserialize<object>(jsonString)
You need System.Web.Extensions dll and import the following namespace.
Namespace: System.Web.Script.Serialization
for more info MSDN
I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.
As #Maloric mentioned in his answer to this question:
var jo = JObject.Parse(myJsonString);
To use JObject, you need the following in your class file
using Newtonsoft.Json.Linq;
Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.
It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.
And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D
There is a System.Json.dll you should add to your project References.
-Jesse
Since you mentioned that you are using Newtonsoft.dll you can convert a JSON string to an object by using its facilities:
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(your_json_string);
[Serializable]
public class MyClass
{
public string myVar {get; set;}
etc.
}

Json Object Deserialization in c#

im tyring to deserialize my object coming from client side having following format:
{'goalplans':
[{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0}
]}
thing is that im not able to deserialze it on my server side .
Please tell me how can i deserialize the Json object to a list object like
List . i tried many ways but not working.
serialize/deserialize objects to/from JSON exist Since .NET 3.5, try this
using System.Web.Script.Serialization;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
See here for more details
Hope this helps
One possible third party component is JSON.NET. Personally I have made very good experience with that library ( it is available using nuget for example )
I solved the problem by myself. Simply adding [Serializable] to my class
and changed method to take argument of class type ...
e.g.
//My class
[Serializable]
public class GoalPlanList{}
//method
public static int GoalplanAddUPD(List<GoalPlanList> goalplans)
{
foreach (GoalPlanList goals in goalplans)
{}
}

Categories