JSON change value - c#

I have a JSON value like this
{"$id":"649271776","$type":"outdoorgame","Overs":50,"Balls":6,"TeamName":"TestTeam"}
I wrote a C# code like this to change the value of Overs from 50 to 10
var jsonString = sSession.GameState; //this is the value {"$id":"649271776","$type":"outdoorgame","Overs":50,"Balls":6,"TeamName":"TestTeam"}
dynamic jsonObject =
Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
jsonObject.Overs = 10;
var modifiedJsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject);
This code is changing the value of Overs from 50 to 10. The problem I am facing when I use the above code modifiedJsonString is missing these two values
"$id":"649271776","$type":"outdoorgame"
giving the output as {Overs":10,"Balls":6,"TeamName":"TestTeam"} I want $id and $type also in the modifiedJsonString.
I want modifiedJsonString like this {"$id":"649271776","$type":"outdoorgame","Overs":10,"Balls":6,"TeamName":"TestTeam"}
Can anyone tell me how to solve this problem

The problem is that $id and $type are not valid identifiers, and can't appear as members of the returned dynamic object built by the JSON serializer. As in gldraphael's answer, the solution is to create your own concrete class to hold the deserialized object; for the properties whose names start with $ you'll need to use JsonPropertyAttribute to remap the names:
public class GameState
{
[JsonProperty("$id")] public string ID { get; set; }
[JsonProperty("$type")] public string Type { get; set; }
int Overs { get; set; }
int Balls { get; set; }
public string TeamName { get; set; }
}
Further, Json.NET treats $type as a special property name and this interferes with proper deserialization of your object. To get around this, we must use the MetadataPropertyHandling.Ignore serializer setting.
Thus you can deserialize, modify and re-serialize like this:
string jsonString = "{\"$id\":\"649271776\",\"$type\":\"outdoorgame\",\"Overs\":50,\"Balls\":6,\"TeamName\":\"TestTeam\"}";
JsonSerializerSettings settings = new JsonSerializerSettings() { MetadataPropertyHandling = MetadataPropertyHandling.Ignore };
GameState jsonObject = JsonConvert.DeserializeObject<GameState>(jsonString, settings);
jsonObject.Overs = 10;
var modifiedJsonString = JsonConvert.SerializeObject(jsonObject);
See it in action.

You can use JToken to handle this.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var jsonString = "{\"$id\":\"649271776\",\"$type\":\"outdoorgame\",\"Overs\":50,\"Balls\":6,\"TeamName\":\"TestTeam\"}";
JToken jsonObject = JToken.Parse(jsonString);
jsonObject["Overs"] = 10;
var modifiedJsonString = JsonConvert.SerializeObject(jsonObject);
// In case one wanted to update the $type and $id fields
jsonObject["$type"] = "asdf";
jsonObject["$id"] = 123456;
var modifiedJsonString2 = JsonConvert.SerializeObject(jsonObject);
Will result in:
modifiedJsonString --> {"$id":"649271776","$type":"outdoorgame","Overs":10,"Balls":6,"TeamName":"TestTeam"}
And if you needed to update $id and $type, that is possible, too.
modifiedJsonString2 -->
{"$id":123456,"$type":"asdf","Overs":10,"Balls":6,"TeamName":"TestTeam"}
Demo on .NET Fiddle: https://dotnetfiddle.net/a370Mv

Use a concrete class. You'll need to annotate the fields with $ prefixes manually. Eg:
public class Example
{
public string Field { get; set; }
[JsonProperty("$type")]
public string Type { get; set; }
}
Here's a working example.
In your case the class will look something like:
public class ObjName
{
[JsonProperty("$id")]
public string Id { get; set; }
[JsonProperty("$type")]
public string Type { get; set; }
public int Overs { get; set; }
public int Balls { get; set; }
public string TeamName { get; set; }
}
(Just be mindful of the property case).

Related

UWP C# - How to deserialize JsonObject into a class using Windows.Data.Json?

I don't want to use Newtonsoft's Json.Net library. I'm avoiding any third-party dependencies if I can help it in this project.
If I have JSON that looks like this:
{
"has_more_items": false,
"items_html": "...",
"min_position": "1029839231781429248"
}
and I have a class that looks like this:
public class TwitterJson
{
bool hasMore { get; set; } // has_more_items
string rawText { get; set; } // items_html
string nextKey { get; set; } // min_position
}
and I have a JsonObject containing the above JSON:
JsonObject theJson = JsonObject.Parse(result);
How do I deserialize the JsonObject into my class? I've been trying to find a clear example of this, and everything I've found uses Json.Net.
I've been trying to find a clear example of this, and everything I've found uses Json.Net.
Because reinventing existing functionality is a waste of time especially when all the hard work has already been done for you.
If you insist on not using it then you will have to manually construct the object model based on the expected JSON.
For example, assuming publicly available properties
public class TwitterJson {
public bool hasMore { get; set; } // has_more_items
public string rawText { get; set; } // items_html
public string nextKey { get; set; } // min_position
}
Then parsing the above to the desired object model
JsonObject theJson = JsonObject.Parse(result);
var model = new TwitterJson {
hasMore = theJson.GetNamedBoolean("has_more_items"),
rawText = theJson.GetNamedString("items_html"),
nextKey = theJson.GetNamedString("min_position")
};
As mentioned by #Dimith, you need to decorate your class with [DataContract] and [DateMember], Please refer to below code which will convert your JSON into a given object.
// Deserialize a JSON string to a given object.
public static T ReadToObject<T>(string json) where T: class, new()
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return ser.ReadObject(stream) as T;
}
}
Class:
[DataContract]
public class TwitterJson
{
[DataMember(Name = "has_more_items")]
bool hasMore { get; set; } // has_more_items
[DataMember(Name = "items_html")]
string rawText { get; set; } // items_html
[DataMember(Name = "min_position")]
string nextKey { get; set; } // min_position
}
Sample on how to use:
var result = "{\"has_more_items\": false, \"items_html\": \"...\",\"min_position\": \"1029839231781429248\"}";
var obj = ReadToObject<TwitterJson>(result);
You have to decorate your class with [DataContract] and [DataMember] attributes. Write the json into a memory stream and deserialize using DataContractJsonSerializer
Here is a more elaborated sample.
In addition to #Nkosi's answer below are some Comparisons between JSON.net and other alternatives:
JSON.Net vs DataContractJsonSerializer
JSON.Net vs Windows.Data.Json

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();

Unable to map JSON response to a predefined class in C# / dynamic property name

I have a class which basically contains a property like this:
public class Msg
{
[JsonProperty(PropertyName = "XD1703301059485299")]
public Shipping shipping { get; set; }
}
the problem is in this part:
[JsonProperty(PropertyName = "XD1703301059485299")]
And the dynamic property name that I get from server...
This property name can be any name that server returns. In this particular case it's able to map the JSON to my class since the property names are same... But when server returns something like this:
XS12394124912841
The object is the null....
How can I resolve property name to be dynamic ? Can someone help me out?
P.S. This is the JSON response itself:
{"status":1,"msg":{"dynamic_name":{"order_sn":"12312313123123123","order_status":"0","shipping_info":[{"shipping_name":"","shipping_no":"","shipping_img":"","shipping_code":"","shipping_time":"","track_goods":""}]}},"errcode":0}
So I don't think this problem is as dynamic as it sounds. You can probably just convert to a dyanmic object and explicitly handle conversions.
Sample solution below. I inserted a few values to show conversion works as expected.
Add nuget package Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace Serialize
{
public class Shipping
{
[JsonProperty(PropertyName = "shipping_name")]
public String Name { get; set; }
[JsonProperty(PropertyName = "shipping_img")]
public String Img { get; set; }
[JsonProperty(PropertyName = "shipping_code")]
public String Code { get; set; }
}
public class Order
{
public Shipping shipping { get; set; }
[JsonProperty(PropertyName = "order_sn")]
public string SerialNumber { get; set; }
[JsonProperty(PropertyName = "order_status")]
public string Status { get; set; }
}
class Program
{
static void Main(string[] args)
{
/*
{
"status":1,
"msg": {
"dynamic_name": {
"order_sn": "12312313123123123",
"order_status":"0",
"shipping_info": [{
"shipping_name":"name",
"shipping_no":"",
"shipping_img":"img",
"shipping_code":"code",
"shipping_time":"",
"track_goods":""
}]
}
},
"errcode":0
}
* */
var raw = "{ \"status\":1, \"msg\":{\"dynamic_name\":{\"order_sn\":\"12312313123123123\",\"order_status\":\"0\",\"shipping_info\":[{\"shipping_name\":\"name\",\"shipping_no\":\"\",\"shipping_img\":\"img\",\"shipping_code\":\"code\",\"shipping_time\":\"\",\"track_goods\":\"\"}]}},\"errcode\":0}";
var incomingOrder = new Order();
// properties on dynamic objects are evaluated at runtime
dynamic msgJson = JObject.Parse(raw);
// you'll want exception handling around all of this
var order = msgJson.msg.dynamic_name;
// accessing properties is easy (if they exist, as these do)
incomingOrder.SerialNumber = order.order_sn;
incomingOrder.Status = order.order_status;
// JObject cast might not be necessary. need to check for array elements, etc.
// but it's simple to serialize into a known type
incomingOrder.shipping = ((JObject)(order.shipping_info[0])).ToObject<Shipping>();
}
}
}
Alternatively, if the property name is given at runtime, you can dereference properties with the indexer getter
dynamic msgJson = JObject.Parse(raw);
JObject order = msgJson.msg["XS12394124912841"];
incomingOrder.SerialNumber = order["order_sn"].ToObject<string>();
incomingOrder.Status = order["order_status"].ToObject<string>();
incomingOrder.shipping = order["shipping_info"][0].ToObject<Shipping>();
You can implement something like this with the help of System.Web.Helpers
using (StreamReader r = new StreamReader("sample.json"))
{
string json = r.ReadToEnd();
dynamic data = Json.Decode(json);
Console.WriteLine(data["your_property"]);
}
Here sample.json contains your sample JSON response.

Modify a JSON string

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; }
}

How Can I Deserialize JSON Data Using C#?

I have seen some other questions like this, but those are quite complex JSON data's that have objects within objects. Although the JSON I'm working with is never static, I doubt it's as complex as those. Also, it's my first time using JSON with C# so I'm a little clueless.
What I'm trying to achieve is to separate the data that is received from an API that I prompt using WebRequest in C#.
{
"johhny.debt": {
"id":35187540,
"name":"johnny.debt",
"profileIconId":786,
"Level":30,
"revisionDate":1428019045000
}
}
The returned JSON data is in a fashion like thereof.
I want to be able to access all of the properties of the above string in the following manner:
ID :
Name:
~~
~~
~~
... and so forth.
I'm assuming some type of class has to be made for this?
All help is appreciated, thank you all in advance.
Install Json.Net from Nuget
Install-Package Newtonsoft.Json
https://www.nuget.org/packages/Newtonsoft.Json/
Declare class for inner object ({"id":..., "name": ... }):
public class InnerObject
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Username { get; set; }
[JsonProperty("profileIconId")]
public int ProfileIconId { get; set; }
[JsonProperty("level")]
public int Level { get; set; }
[JsonProperty("revisionDate")]
public string RevisionDate { get; set; }
}
As you can see you can specify rename mapping from json fields to .Net object properties using JsonPropertyAttribute.
Read your json to Dictionary<string,InnerObject> and get value of "johhny.debt" key:
var dict = JsonConvert.DeserializeObject<Dictionary<string, InnerObject>>(jsonText);
var johhny = dict["johhny.debt"];
Or if your need always to parse exact json property 'johhny.debt', you could create root object class:
public class RootObject
{
[JsonProperty("johhny.debt")]
public InnerObject JohhnyDept { get; set; }
}
And deserialize it:
var root = JsonConvert.DeserializeObject<RootObject>(jsonText);
var johhny = root.JohhnyDebt;
Just Create a class like this
public class RootObject
{
public int Id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int Level { get; set; }
public string revisionDate { get; set; }
}
then install json.Net and this code to your main method
var jsonObject=JsonConvert.DeserializeObject<RootObject>(jsonText);
That's all
Update
var obj = JObject.Parse(json);
var RootObject = new RootObject()
{
Id = (int)obj["johhny.debt"]["id"],
Level = (int)obj["johhny.debt"]["Level"],
name = (string)obj["johhny.debt"]["name"],
profileIconId = (int)obj["johhny.debt"]["profileIconId"],
revisionDate = (string)obj["johhny.debt"]["revisionDate"]
};

Categories

Resources