[英]Convert comma seperated string to json
I have a comma seperated string value like 我有一个逗号分隔的字符串值,例如
100,140
100,140
i need to convert that into a json string. 我需要将其转换为json字符串。 that should be like
那应该像
{"person":[{"id":"100"},{"id":"140"}]}
{“ 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: 考虑到您使用Json.net库 ,我建议首先使用逗号将字符串拆分为数组并将其序列化为字符串:
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. 在我的示例中,我序列化了一个动态类型,但是您可以使用ids数组实现自定义类Person。
In MVC you have Json serialiser in conrollers. 在MVC中,控制器中有Json序列化器。 Just create model that describes your json in your case it will be:
只需创建描述您的json的模型即可:
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);
}
first split your string and store in an array. 首先将您的字符串拆分并存储在数组中。 Then convert your strings to jsonObjects.
然后将您的字符串转换为jsonObjects。 Add jsonobjects to jsonarray.
将jsonobjects添加到jsonarray。 follow the below code .
请遵循以下代码。 it's working.
它正在工作。
string split = "100,140";
string[] datas = split.Split(',');
JsonArray jsonArry = new JsonArray();
JsonObject jsonobj = new JsonObject();
JsonObject jsonobj2 = new JsonObject();
foreach (string data in datas)
{
jsonobj.SetNamedValue("id", JsonValue.CreateStringValue(data));
jsonArry.Add(jsonobj);
}
jsonobj2.SetNamedValue("person", jsonArry);
also you can convert the jsonobject to string. 您也可以将jsonobject转换为字符串。
string jsonString = jsonobj2.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.