Modify a JSON string - c#

I have a string in JSON format as follows
string jsonStr = "{"Type":1, "Id":1000,"Date":null,"Group": "Admin","Country":"India","Type":1}";
I want to modify this string so that Id attribute should always be the first. The order of attributes matters.
Is there any way I can modify this string.
I tried searching google but did not find appropriate solution.
Any help would be appreciated.
EDIT:
I also tried to deserialize object using
object yourOjbect = new JavaScriptSerializer().DeserializeObject(jsonStr);
But here also the "type" attribute comes first. I dont find any way to move the attributes within this deserialized object

It's possible. Use the JsonProperty attribute, property Order.
http://www.newtonsoft.com/json/help/html/JsonPropertyOrder.htm.
Let me know if it works.

Instead of attempting to manipulate the order of the outputted JSON and comparing strings, I would transform both JSON strings that you want to compare, into objects and then perform your comparison. You could then compare individual properties or entire objects with something like the following:
void CompareJSON()
{
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
string jsonToCompare = "JSON TO COMPARE";
MyObject myJsonObject = JsonConvert.DeserializeObject<MyObject>(json);
MyObject myJsonObjectToCompare = JsonConvert.DeserializeObject<MyObject>(jsonToCompare);
if (myJsonObject.Id == myJsonObjectToCompare.Id)
{
// Do something
}
}
class MyObject
{
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}
Please note that this example is carried out using the Newtonsoft.JSON library. More information on the library can be found here.

Just make your JSON into a c# class with Id first and then serialize it again if that is what you need. You do know that you have "Type" twice in the JSON string? In this solution it will get "fixed" so you only have it once as it should be. But if your string really is with two Type this wont work since the strings will be incorrect. If they really are like that you need to do some ugly string manipulation to fix the order but i hope the first string is incorrect only here and not in your code.
private void Test() {
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyJsonObject myJsonObject = jsonSerializer.Deserialize<MyJsonObject>(json);
string s = jsonSerializer.Serialize(myJsonObject);
//Returns: {"Id":1000,"Type":1,"Date":null,"Group":"Admin","Country":"India"}
}
class MyJsonObject {
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}

Related

How to write correct json path?

I have a json object like that:
And i want to access the "question" field throught this code-line:
string msg = (json1["data"][0]["question"]).ToString();
But it doesnt work, why?
But it doesnt work, why?
Because you need to look at the json again.
"data" is an object, not an array. As such "[0]" is not valid as it would access the first element of the array. The only array you have in there is the "answers" element. "question" is directly a property of "data".
Prepare a C# Model like below
public class rootClass
{
public bool ok { get; set; }
public data data { get; set; }
}
public class data
{
public string question { get; set; }
public string[] answers { get; set; }
public int id { get; set; }
}
and use JsonConvert(Newtonsoft dll) class to deserialise and access like below
rootClass rootClass = JsonConvert.DeserializeObject<rootClass>(inputJson);
string msg = rootClass.data.question;

How to deserialize JSON with spaces in the attribute names?

I have a string array that I want to deserialize. Essentially, it is just a list of objects. Note that the attributes have spaces in the names:
[ { \"Event Name\": \"Hurricane Irma PR\", \"Storm Start (LST)\": \"2017-08-30\", \"Storm End (LST)\": \"2017-09-13\", \"Grid Cell Number\": 16412, \"Grid Cell State\": \"PR\", \"Grid Cell Name\": \"Grid26_0\", ...
I created a public class to template the string based on specific attributes that I want ( I don't want all the data) but I am not sure how to handle for the spaces in the names of the attributes that I want.
public class New_Events_Dataset
{
public string EventName { get; set; }
public string StormStart { get; set; }
public string StormEnd { get; set; }
public string GridCellState { get; set; }
public string GridCellName { get; set; }
public string USGSGageSiteNo { get; set; }
public string ReturnPeriodatGridCell { get; set; }
}
When I apply the deserializer with my class New_Events_Dataset like this:
var jsonResponse = returnJson.Deserialize<List<New_Events_Dataset>>(strresult);
string json = new JavaScriptSerializer().Serialize(jsonResponse);
return json;
I end up returning something like this. What am I doing wrong?
[{"EventName":null,"StormStart":null,"StormEnd":null,"GridCellState":null,"GridCellName":null,"USGSGageSiteNo":null,"ReturnPeriodatGridCell":null}
Unfortunately keys must match exactly each other.
One of the best ways to solve your problem is to define JsonProperty attribute for each property to get Deserialized object correctly. You can specify property's json key name with it.
You can take a look to this question and it's answer for better understanding:
An example of JsonProperty
Edit:
As in comments mentioned, because you are using JavaScriptSerializer JsonPropertyAttribute doesn't work in this situation.
But you can use it by adding Newtonsoft.Json Nuget Package and using it's deserilizer this way:
JsonConvert.DeserializeObject<AzureResourceData>(jsonString);

How can parse dynamic json in c#?

Have some json and parse that whit this code:
dynamic json = JsonConvert.DeserializeObject(response.Content);
dynamic result =json.result;
after this line:
dynamic result =json.result;
have this output:
{
{
"321":{
"online_status":true,
"basic_info":{
"status":"Recharged",
"group_name":"IRN-UV002-M01",
"isp_name":"Main",
"creation_date":"2017-09-05 08:19:32",
"recharge_deposit":0.0,
"user_id":321,
"nearest_exp_date":"2018-02-22 10:21:00",
"credit":20387.775145462037,
"deposit":0.0,
"isp_id":0,
"group_id":72
},
"user_repr":"10001168-2100104f4Y8-FTTH",
}
}
}
and now want to get user_id from that json,how can i write code for that purpose?thanks.
The better way would be to deseralize this into a strongly typed object.
But for you you can use the JObject class to do something like the following (note not tested, but you should understand the concept):
dynamic result = JObject.Parse(source);
int id = result.321.basic_info.user_id;
You probably want to do something like this:
var yourInstance = JsonConvert.DeserializeObject<YourClass>(responseJson);
For that, you need to define a class YourClass and related sub-classes which have properties matching the values returned in the JSON data, i.e. something like:
public class YourClass {
public bool online_status { get; set; }
public BasicInfo basic_info { get; set; }
public string user_repr { get; set; }
}
public class BasicInfo {
public string status { get; set; }
public string group_name{ get; set; }
public string isp_name{ get; set; }
public DateTime creation_date{ get; set; }
public string group_name{ get; set; }
// ...etc.
}
With this in place, JsonConvert should be able to understand and parse your data to the correct object.
This is just a rough example, but it should get you on your way.
Another way is to use JObject to hold the string.
var str = "{\"321\":{\"online_status\":true,\"basic_info\":{\"status\":\"Recharged\",\"group_name\":\"IRN-UV002-M01\",\"isp_name\":\"Main\",\"creation_date\":\"2017-09-05 08:19:32\",\"recharge_deposit\":0.0,\"user_id\":321,\"nearest_exp_date\":\"2018-02-22 10:21:00\",\"credit\":20387.775145462037,\"deposit\":0.0,\"isp_id\":0,\"group_id\":72},\"user_repr\":\"10001168-2100104f4Y8-FTTH\"}}";
var obj = JObject.Parse(str);
var userId = obj["321"]["basic_info"]["user_id"].ToString();

How to deserialize JSON date time from MongoDB to C# class

I'm using c# driver to interact with mongoDB.
I have a class that I created and which I populate with the data I get from mongoDB.
One of the properties in that class is DateTime.
The value I get from mongo is /\Date(number)/. Which is ok because this is what I'm suppose to return to the client.
The value that I get from mongo after I retrieve the data is ISODate(some number).
I get an exception: "Invalid JSON primitive: ISODate".
How can I configure mongoDB to save the DateTime like I got it i.e. /\Date(number)/?
Sorry L.B - I didn't noticed your answer but went straight to the answer I was given.
Here's the class I'm trying to deserialize:
public class EventDate
{
public EventDate()
{
}
public int? VenueConfigID { get; set; }
public string Category { get; set; }
public DateTime DateAndTime { get; set; }
public string DisplayDate { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string ShortNote { get; set; }
public string Home { get; set; }
public int? ID { get; set; }
public string Name { get; set; }
}
Here's how I deserialize it:
mongo = MongoServer.Create();
mongo.Connect();
db = mongo.GetDatabase("productionDB");
var col = db.GetCollection<BsonDocument>("eventDates");
var query = Query<PerformerDates>.EQ(ev => ev.PerformerID, performerId);
//MongoCursor<BsonDocument> performer = col.Find(query);
MongoCursor<BsonDocument> performer = col.FindAll();
JavaScriptSerializer js = new JavaScriptSerializer();
List<EventDate> finalMatchedDates = new List<EventDate>();
foreach (var p in performer)
{
//System.Threading.Tasks.Task<EventDate[]> obj2 = JsonConvert.DeserializeObjectAsync<EventDate[]>(p.Elements.ToList()[3].Value.ToString());
EventDate[] obj3 = JsonConvert.DeserializeObject<EventDate[]>(p.Elements.ToList()[3].Value.ToString());
}
mongo.Disconnect();
Solved!!
Eventually I solved it. I used a string instead of a DateTime. When I get it from the DB, I convert it to a DateTime and when I sent it back to the client I serialize it with the format of: /\Date()/
Just use BsonSerializer.Deserialize method.
MongoDB's serializer has a much higher performance over NewtonSoft's Json.Net or Microsoft's DataContractSerializer.
Very common occurring problem! One solution is to use JSON.NET.
See this answer for more help. Although you might be confused with JSON DateTime object but don't worry. It will work!
string json; // Assign JSON here.
var v = Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>(json);

C# Json Deserialization

I have been asked to work with json data in order to create a quiz game in windows phone. I knew that I had to use json.net to achive this which I have previously used in the past but the method I used in the past is no useful here.
My question is this. I have this json string
[{"corr":"1","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"1","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"1","q":"text.","type":"0"},
{"corr":"4","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"2","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"1","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"2","q":"text","a":["22,2%","45%","54%","67%"],"type":"1"}]
and as you can image I want to fill some List with the properties above.
I have created the following class in order to represent the json objects
public class QuizObj
{
public string corr { get; set; }
public string q { get; set; }
public string type { get; set; }
public List<string> a { get; set; }
}
but I don't really know how to use it and can't find something really relevant.
Something like this should do the trick:
var quizObjs = JsonConvert.DeserializeObject<List<QuizObj>>(serializedStringValue);
string corr = quizObjs.First().corr;
// or
foreach(var quizObj in quizObjs)
{
string corr = quizObj.corr;
// etc
}
You will need to add a reference to NewtonSoft.Json, which you can get via NuGet (if you haven't already).

Categories

Resources