Convert comma seperated string to json - c#

I have a comma seperated string value like
100,140
i need to convert that into a json string. that should be like
{"person":[{"id":"100"},{"id":"140"}]}
Please help me with a solution.

Considering you use a Json.net library, I suggest first to split your string to an array by comma andserialize it to a string:
var ids = "100,140".Split(',');
var personsString = JsonConvert.SerializeObject(new { person = ids.Select(x => new { id = x }).ToList()});
In my example, i serialize a dynamic type, but you can implement your custom class Person with ids array.

first split your string and store in an array.
Then convert your strings to jsonObjects.
Add jsonobjects to jsonarray.
follow the below code . it's working.
String split = "100,140";
String[] datas = split.split(",");
JsonArray jsonArry = new JsonArray();
for (String data : datas)
{
JsonObject jsonobj = new JsonObject();
jsonobj.addProperty("id",data);
//jsonobj.SetNamedValue("id", JsonValue.CreateStringValue(data));
jsonArry.add(jsonobj);
}
JsonObject jsonobj2 = new JsonObject();
//jsonobj2.SetNamedValue("person", jsonArry);
jsonobj2.addProperty("person", jsonArry);
//also you can convert the jsonobject to string.
String jsonString = jsonobj2.ToString();

In MVC you have Json serialiser in conrollers. Just create model that describes your json in your case it will be:
public class Model
{
public IEnumerable<Person> person { get; set; }
}
public class Person
{
public int id { get; set; }
}
And then in your controller you are able to do this:
public JsonResult GetData()
{
var str = "100,140"; // your string
Model model = new Model();
//parse string to model
model.person = str.Split(',').Select(x => new Person { id = Convert.ToInt32(x) });
//serialize to json
return Json(model);
}

Related

How to desearilize Json and bind to variables/properties c#

var AdditionalData = flexEventTriggerLogsList.Select(x => x.AdditionalData).ToString();
string json = Convert.ToString(JsonConvert.DeserializeObject(AdditionalData));
var objTriggerLog = new FlexEventTriggerLog();
objTriggerLog.lookupEntity_RecordId = ????
objTriggerLog.DocumentRecordIds = ????
Additinal data wil return my Json object in string. I have to use that object to get my entity and document record ids.
Json object which will be returned:
{
"lookupEntity_RecordId": "00000000-0000-0000-0000-000000000000",
"DocumentRecordIds":["00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000"]
}
You can use JsonConvert.DeserializeObject(jsonstring)
You create a model for your json
public class AdditionalDataModel
{
public string lookupEntity_RecordId { get; set; }
public List<string> DocumentRecordIds { get; set; }
}
then deserialize your json in model
var AdditionalData = flexEventTriggerLogsList.Select(x => x.AdditionalData).ToString();
var additionalDataModel = JsonConvert.DeserializeObject<AdditionalDataModel>(AdditionalData);
var objTriggerLog = new FlexEventTriggerLog();`
objTriggerLog.lookupEntity_RecordId = additionalDataModel.lookupEntity_RecordId;
objTriggerLog.DocumentRecordIds = additionalDataModel.DocumentRecordIds;

Loop through JSON object and values to List in C#

I am trying to get values from a JSON object and save them into 2 lists. I am struggling with understanding how to loop through the JSON object to get the JSON array values.
I believe I am Deserializing correctly, but I am stuck going forward. Here is what I currently have
JObject jsonResult = {"foodtype": ["Pizza", "Pasta", "Bread"],
"drinks": ["Coke", "Root Beer"]}
public class Rootobject
{
public string[] foodType { get; set; }
public string[] drinks { get; set; }
}
var allObject = JsonConvert.DeserializeObject<Rootobject>(jsonResult.ToString());
What I am wanting is for 2 lists to be generated from the JSON result like so:
List<string> food = new List<string> {Pizza, Pasta, Bread}
List<string> drink = new List<string> {Coke, Root Beer}
Your code is invalid, the snippet below is incorrect:
JObject jsonResult = {"foodtype": ["Pizza", "Pasta", "Bread"],
"drinks": ["Coke", "Root Beer"]}
You need to have a string which can be deserialized.
The code below should help you:
static void Main(string[] args)
{
var objectToSerialize = new Rootobject()
{
Drinks = new [] {"Coke", "Root Beer" },
FoodType = new[] { "Pizza", "Pasta", "Bread" }
};
var serializedByTheLib = JsonConvert.SerializeObject(objectToSerialize);
string jsonResult =
"{ \"foodtype\": [\"Pizza\", \"Pasta\", \"Bread\"], \"drinks\": [\"Coke\", \"Root Beer\"] }";
var deserializedObject = JsonConvert.DeserializeObject<Rootobject>(jsonResult);
}
public class Rootobject
{
[JsonProperty("foodType")]
public string[] FoodType { get; set; }
[JsonProperty("drinks")]
public string[] Drinks { get; set; }
}
Key concepts:
An object can be serialized to JSON
A JSON string can be deserialized to an Object
Take a look at newtonsoft documentation to get more info
When you have deserialized the json string to your Rootobject, you can just pick the properties of it:
string json = "{\"foodtype\": [\"Pizza\", \"Pasta\", \"Bread\"], \"drinks\": [\"Coke\", \"Root Beer\"]}";
Rootobject rootObject = JsonConvert.DeserializeObject<Rootobject>(json);
List<string> food = rootObject.foodType.ToList();
List<string> drinks = rootObject.drinks.ToList();

Create JSON object from string in C#

I am trying to create a JSON string which contains one container and one array.
I can do this by using a stringbuilder but I am trying to find a better way to get the JSON string; I want:
{ "message":{ "text":"test sms"},"endpoints":["+9101234"]}
I tried this:
string json = new JavaScriptSerializer().Serialize(new
{
text = "test sms",
endpoints = "[dsdsd]"
});
And the output is:
{"text":"test sms","endpoints":"[dsdsd]"}
Any help or suggestions how to get the required format?
In the most recent version of .NET we have the System.Text.Json namespace, making third party libraries unecessary to deal with json.
using System.Text.Json;
And use the JsonSerializer class to serialize:
var data = GetData();
var json = JsonSerializer.Serialize(data);
and deserialize:
public class Person
{
public string Name { get; set; }
}
...
var person = JsonSerializer.Deserialize<Person>("{\"Name\": \"John\"}");
Other versions of .NET platform there are different ways like the JavaScriptSerializer where the simplest way to do this is using anonymous types, for sample:
string json = new JavaScriptSerializer().Serialize(new
{
message = new { text = "test sms" },
endpoints = new [] {"dsdsd", "abc", "123"}
});
Alternatively, you can define a class to hold these values and serialize an object of this class into a json string. For sample, define the classes:
public class SmsDto
{
public MessageDto message { get; set; }
public List<string> endpoints { get; set; }
}
public class MessageDto
{
public string text { get; set; }
}
And use it:
var sms = new SmsDto()
{
message = new MessageDto() { text = "test sms" } ,
endpoints = new List<string>() { "dsdsd", "abc", "123" }
}
string json = new JavaScriptSerializer().Serialize(sms);

JSON.Net Convert inner object to C# Model

I have the following JSON coming back from a remote API (I cannot modify the JSON returned)
{
"APITicket": {
"location": "SOMEVALUE",
"ticket": "SOMEVALUE"
}
}
Now using JSON.Net to convert to this to a model I have to create 2 models.
public class TicketModel
{
public string location { get; set; }
public string ticket { get; set; }
}
public class TicketContainer
{
public TicketModel APITicket { get; set; }
}
and do something like..
var myObject = JsonConvert.DeserializeObject<TicketContainer>(this.JSONResponse);
and this works well - my problem arises when I have around 50 calls to make to the API and really dont fancy creating a second 'Container' for each. Is there a way to bind the example above directly to the TicketModel?
You can do it this way:
var json = #"
{
'APITicket': {
'location': 'SOMEVALUE',
'ticket': 'SOMEVALUE'
}
}";
//Parse the JSON:
var jObject = JObject.Parse(json);
//Select the nested property (we expect only one):
var jProperty = (JProperty)jObject.Children().Single();
//Deserialize it's value to a TicketModel instance:
var ticket = jProperty.Value.ToObject<TicketModel>();
use Newtonsoft's JArray to customize ur json before deserialize
public List<APITicket> JsonParser(string json)
{
Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.Parse(json);
var list = new List<APITicket>();
foreach(var item in jArray)
{
list.Add(
new APITicket { location = item["APITicket"]["location"],
ticket = item["APITicket"]["ticket"]
}
);
}
return list;
}
Modify the JSON so it looks like this
{
"location": "SOMEVALUE",
"ticket": "SOMEVALUE"
}
and do
List<TicketModel> tickets = JsonConvert.DeserializeObject<List<TicketModel>>(this.JSONResponse);
or even
Dictionary<string, string> tickets = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.JSONResponse);
so you don't need any models.

Deserialize JSON string to c# object

My Application is in Asp.Net MVC3 coded in C#.
This is what my requirement is. I want an object which is in the following format.This object should be achieved when I deserialize the Json string.
var obj1 = new { arg1=1,arg2=2 };
After using the below code:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize<object>(str);
The object what i get i.e obje does not acts as obj1
Here, in this example my JSON string is static, but actually JSON string is going to be dynamically generated runtime, so i won't be able get Arg1 and Arg2 all the time.
I think the JavaScriptSerializer does not create a dynamic object.
So you should define the class first:
class MyObj {
public int arg1 {get;set;}
public int arg2 {get;set;}
}
And deserialize that instead of object:
serializer.Deserialize<MyObj>(str);
Not testet, please try.
Use this code:
var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);
I believe you are looking for this:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());
This may be useful:
var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use
myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);
Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).
solution :
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:
string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
{
json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());
}
//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(#json);
memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
{
var serializer = new DataContractJsonSerializer(typeof(MyType));
myType = (MyType)serializer.ReadObject(jsonReader);
}
}
4 Sure it will work.... ;)

Categories

Resources