2

I am new to C#. I want to convert the two strings to single JSON array.
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/

Convert string to Json Array

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

convert string to json

To learn how to convert my string to Json array. Well explained in the above url, but for my case I don't know how to convert this two string to single Json array.

I want the output to be like this format,

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

Please help me in doing this.

Community
  • 1
  • 1
user3100575
  • 153
  • 2
  • 2
  • 7
  • If you program in C#, you need to obey C# syntax, obviously... For a start, try simple string concatenation, like `var json_data = "result\":[{\"username\":" + username + ",\"password\":" + ...`. If you got a feeling for it, then look at [string.Format()](http://msdn.microsoft.com/en-us/library/system.string.format.aspx), which will make life easier for you. –  Jun 07 '14 at 10:59
  • As elgonzo said, but from your example it looks like you need to look in particular how to put doubles quote characters into strings, so look in particular at `var withBackslahes = " \" ";` and `var verbatim = @" "" ";`. – ClickRick Jun 07 '14 at 11:05

5 Answers5

7

You can use a JSON serialiser API. A commonly used one is the one from Newtonsoft, called 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).

In your example, Newtonsoft JSON API can be used as follows.

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.

bytefire
  • 4,156
  • 2
  • 27
  • 36
  • Do i need to import any class to use this API.My application may have to work in offline mode also,so do this API work in offline if not how to handle this.Please let me know. – user3100575 Jun 07 '14 at 11:19
  • 1
    You will need to reference the API into your project. Once that is done, you don't need Internet for it to execute. – bytefire Jun 07 '14 at 11:20
  • You may need to google how to add reference to Json.NET (or any NuGet API) in Visual Studio 2010. But that's a one-off effort which will help you throughout your C# development. – bytefire Jun 07 '14 at 11:28
  • This code won't compile, because the fields of `UserData` are private. You could simply make them public, but I think a better option would be to use anonymous object: `var userData = new { username = "Tom", password = "XXXXXXXX" };`. – svick Jun 07 '14 at 11:38
  • @svick thanks, made them public. I thought of anonymous at first but OP wanted an array and to make an array of anonymous objects might have made the example a bit difficult to follow for a C# starter. – bytefire Jun 07 '14 at 11:55
  • What's so difficult about `var arr = new[] { userData };`? – svick Jun 07 '14 at 12:14
1

To extend bytefire's answer, there are a couple of ways this can be achieved:

  1. Create a class with the desired properties, in your case username and password. I will annotate the properties with JsonProperty from Json.NET so the serializer can match them disregarding lower/uppercase:

    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:

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:

    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();
    }
    
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
0

Or one of many alternatives: simple Json, if you think JSON.net is way too huge.

neutrino
  • 169
  • 1
  • 3
0

In Javascript Object Notation the top level is always an object.

In JSON an array is not an object but it can be a value.

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" } ] }
Johannes
  • 6,490
  • 10
  • 59
  • 108
0

Simplest way I came across. It worked for me when I wanted to parse a JSON i get from YelpAPI.

  1. Paste JSON as classes in your visual studio or another IDE
  2. Request the API and get the JSON content in var contentJSON.
  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 .

    var contentJson = await SendRequest(request);

    dynamic response = JsonConvert.DeserializeObject(contentJson);

    List 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. Code:

Dhrumil Panchal
  • 406
  • 5
  • 11
  • simple? "Paste JSON as classes in your visual studio or another IDE" - how? the fact I'm having to ask means it's not simple. – Paul McCarthy Jan 05 '23 at 13:37