2013-07-30 19 views
5

Sto usando questo metodo per formare la stringa json e questo funziona correttamente. Ma non posso gestirlo se contiene più proprietà. C'è qualche altro metodo migliore di questo?Forming Json Format String

string.Format("{0}{1}longUrl{1}:{1}{2}{1}{3}", "{", "\"", longUrl,"}"); 

L'uscita è

{"longUrl":"http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72"} 

risposta

8

Beh, un modo "migliore" di fare questo potrebbe essere quella di utilizzare una libreria JSON. Se questo è nel contesto di un sito Web Asp.Net (nelle ultime versioni), esiste la libreria Json.Net a cui viene fatto automaticamente riferimento. In caso contrario, è possibile utilizzare Nuget per aggiungere un riferimento al progetto o aggiungerlo manualmente, a seconda del caso. Si potrebbe poi fare:

JsonConvert.SerializeObject(new { longUrl = longUrl }); 

Si noti che si può anche semplicemente usare new { longUrl } e il nome della proprietà sarà lo stesso del vostro nome di variabile.

+0

Grazie questo sta lavorando bene ... –

+0

Dovrebbe essere 'JsonConvert.SerializeObject (new {LongURL = LongURL});' però :) – ajgarn

+0

@ajgarn Questo è corretta. Aggiustato. :) –

2

Si potrebbe semplicemente utilizzare un serializzatore JSON come JSON.NET. In mancanza di questo, è possibile semplificare un po ':

string.Format(@"{{""longUrl"":""{0}""}}", longUrl); 
+0

Credo che non funzionerà. Ci sono più {e} diversi da {0} e questo è problematico per string.Format(). – wooohoh

1

Si può usare Newtonsoft.Json:

using System.Text; 
using Newtonsoft.Json; 
using System; 
using System.IO; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var d = new 
     { 
      longUrl = "http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72", 
      someOtherProeprty = 1 
     }; 
     var s = new JsonSerializer(); 
     var sb = new StringBuilder(); 
     using (var w = new StringWriter(sb)) 
     { 
      s.Serialize(w, d); 
     } 
     Console.WriteLine(sb.ToString()); 
    } 
} 
0

si può using System.Web.Script.Serialization; poi fare

var dict = new Dictionary<string, string> 
      { 
       {"longUrl","http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72"}, 
       {"anotherUrl", "another Url"} 
      }; 

var serializer = new JavaScriptSerializer(); 
serializer.Serialize(dict); 
7

È possibile utilizzare JSON.Net biblioteca. È possibile creare una classe di entità che si desidera convertire in JSON anziché utilizzare formattatore di stringhe.

per es.

public class Account 
    { 
     public string Email { get; set; } 
     public bool Active { get; set; } 
     public DateTime CreatedDate { get; set; } 
     public IList<string> Roles { get; set; } 
    } 

Account account = new Account 
    { 
    Email = "[email protected]", 
    Active = true, 
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), 
    Roles = new List<string> 
     { 
     "User", 
     "Admin" 
     } 
    }; 

string json = JsonConvert.SerializeObject(account, Formatting.Indented); 

Console.WriteLine(json); 

uscita:

// { 
// "Email": "[email protected]", 
// "Active": true, 
// "CreatedDate": "2013-01-20T00:00:00Z", 
// "Roles": [ 
//  "User", 
//  "Admin" 
// ] 
// } 
+0

+1, grazie per la spiegazione dettagliata –