简体   繁体   English

在C#中将字符串转换为json数组

[英]Convert string to json array in C#

I am new to C#. 我是C#的新手。 I want to convert the two strings to single JSON array. 我想将两个字符串转换为单个JSON数组。
I tried the following: 我尝试了以下方法:

var username = "username";
var password = "XXXXXXXX";
var json_data = "result":[{"username":username,"password":password}]'; //To convert the string to Json array i tried like this
MessageBox.Show(json_data);

It is not working, I'm getting a lot of errors. 它不起作用,出现很多错误。

I've went through the following links: 我浏览了以下链接:

http://json.codeplex.com/ http://json.codeplex.com/

Convert string to Json Array 将字符串转换为Json数组

http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET

convert string to json 将字符串转换为json

To learn how to convert my string to Json array. 了解如何将我的字符串转换为Json数组。 Well explained in the above url, but for my case I don't know how to convert this two string to single Json array. 在上面的网址中有很好的解释,但是对于我来说,我不知道如何将这两个字符串转换为单个Json数组。

I want the output to be like this format, 我希望输出是这种格式,

[{"result":{"username":"Tom","password":"XXXXXXX"}}]

Please help me in doing this. 请帮助我做到这一点。

You can use a JSON serialiser API. 您可以使用JSON序列化器API。 A commonly used one is the one from Newtonsoft, called Json.NET . 一种常用的工具是来自Newtonsoft的工具,称为Json.NET

Job of such an API is to convert C# objects to JSON (also known as serialisation) and convert JSON data into C# objects (deserialisation). 此类API的工作是将C#对象转换为JSON(也称为序列化),并将JSON数据转换为C#对象(反序列化)。

In your example, Newtonsoft JSON API can be used as follows. 在您的示例中,Newtonsoft JSON API可以按以下方式使用。

public class UserData { public string username; public string password; }

var userData = new UserData() { username = "Tom", password = "XXXXXXXX" };

UserData[] arr = new UserData[] { userData };

string json_data = JsonConvert.SerializeObject(arr); // this is the Newtonsoft API method

// json_data will contain properly formatted Json. Something like [{"result":{"username":"Tom","password":"XXXXXXX"}}] 

MessageBox.Show(json_data); 

Excuse my typing as I'm doing it over phone. 通过电话进行打扰时请打扰。

To extend bytefire's answer, there are a couple of ways this can be achieved: 为了扩展bytefire的答案,可以通过以下两种方法实现:

  1. Create a class with the desired properties, in your case username and password . 在您的情况下,创建具有所需属性的类, usernamepassword I will annotate the properties with JsonProperty from Json.NET so the serializer can match them disregarding lower/uppercase: 我将使用来自Json.NET的JsonProperty注释属性,以便序列化程序可以匹配它们而JsonProperty考虑大小写:

     public class User { [JsonProperty(PropertName = username)] public string Username { get; set; } [JsonProperty(PropertName = password)] public string Password { get; set; } } 

Then, serialize your object using JsonConvert.SerializeObject: 然后,使用JsonConvert.SerializeObject序列化您的对象:

var user = new User { Username = "user", Password = "pass" };
var jsonUser = JsonConvert.SerializeObject(user);
  1. Using JsonTextWriter from Json.NET , you can construct a json without creating an object: 使用Json.NET的 JsonTextWriter ,您可以在不创建对象的情况下构造json:

     var stringBuilder = new StringBuilder(); var stringWriter = new StringWriter(stringBuilder); string jsonString = null; using (var jsonWriter = new JsonTextWriter(stringWriter)) { writer.Formatting = Formatting.Indented; writer.WriteStartObject(); writer.WriterPropertyName("username"); writer.WritePropertyValue("user"); writer.WriterPropertyName("password"); writer.WritePropertyValue("pass"); writer.WriteEnd(); writer.WriteEndObject(); jsonString = writer.ToString(); } 

或多种选择之一:如果您认为JSON.net太大,可以使用简单的Json

In Javascript Object Notation the top level is always an object. Javascript对象表示法中 ,顶层始终是一个对象。

In JSON an array is not an object but it can be a value. 在JSON中,数组不是对象,但可以是值。

You can unfold the grammer into this: 您可以将语法展开为:

{ string : [ { string : string , string : string },{ string : string , string : string } ] }

in your case this could be: 在您的情况下,可能是:

{ "allUsers": [ { "name": "Luis" , "password": "R0Cke+" }, { "name": "Janette" , "password": "BookTour2011" } ] }

Simplest way I came across. 我碰到的最简单方法。 It worked for me when I wanted to parse a JSON i get from YelpAPI. 当我想解析从YelpAPI获得的JSON时,它对我有用。

  1. Paste JSON as classes in your visual studio or another IDE 将JSON作为类粘贴到Visual Studio或其他IDE中
  2. Request the API and get the JSON content in var contentJSON. 请求API并在var contentJSON中获取JSON内容。
  3. T here from is one of the classes whose list you would like to make while value 1 exact string used in JSON file . 从这里开始是您想在JSON文件中使用值1确切字符串的情况下列出其类别之一。

    var contentJson = await SendRequest(request); var contentJson =等待SendRequest(request);

    dynamic response = JsonConvert.DeserializeObject(contentJson); 动态响应= JsonConvert.DeserializeObject(contentJson);

    List abc = response.value1.ToObject>(); 列出abc = response.value1.ToObject>();

Note : T and value1 are the same in JSON but when we paste JSON as classes, we get T class and value1 as parent value in JSON tree. 注意:JSON中的T和value1相同,但是将JSON粘贴为类时,在JSON树中将T类和value1作为父值。 Code: 码:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM