将String变量保存在C#中的JSON文件中

时间:2019-11-17 12:05:54

标签: c# json

我有3个变量:

String Phone, Password and Location;
我要另存为json文件中的

phone:"xxxxx",password:"yyyyyy',location:"zzzzz"

上面的JSON是不正确的,我只是为了显示我的需要而已。

我不想在项目中添加额外的类只是为了在JSON文件中保存3个变量。

我首选的库是Newtonsoft.Json

2 个答案:

答案 0 :(得分:6)

您可以像这样序列化匿名类型。

BinaryFileResponse {#449 ▼
  #file: File {#464 ▼
    path: "C:\xampp71\htdocs\storage\app"
    filename: "lorem-ipsum-shop-1.zip"
    basename: "lorem-ipsum-shop-1.zip"
    pathname: "C:\xampp71\htdocs\storage\app/lorem-ipsum-shop-1.zip"
    extension: "zip"
    realPath: "C:\xampp71\htdocs\storage\app\lorem-ipsum-shop-1.zip"
    aTime: 2019-11-14 11:34:52
    mTime: 2019-11-14 11:34:52
    cTime: 2019-11-01 16:05:10
    inode: 0
    size: 24626
    perms: 0100666
    owner: 0
    group: 0
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
    linkTarget: "C:\xampp71\htdocs\storage\app\lorem-ipsum-shop-1.zip"
  }
  #offset: 0
  #maxlen: -1
  #deleteFileAfterSend: false
  +headers: ResponseHeaderBag {#234 ▼
    #computedCacheControl: array:1 [▼
      "public" => true
    ]
    #cookies: []
    #headerNames: array:5 [▼
      0 => 0
      "cache-control" => "Cache-Control"
      "date" => "Date"
      "last-modified" => "Last-Modified"
      "content-disposition" => "Content-Disposition"
    ]
    #headers: array:5 [▼
      0 => array:1 [▶]
      "cache-control" => array:1 [▶]
      "date" => array:1 [▶]
      "last-modified" => array:1 [▶]
      "content-disposition" => array:1 [▼
        0 => "attachment; filename=testdownload.zip"
      ]
    ]
    #cacheControl: array:1 [▼
      "public" => true
    ]
  }
  #content: null
  #version: "1.0"
  #statusCode: 200
  #statusText: "OK"
  #charset: null
}

经过修改以修复对象初始化语法。

此外,如Zohars所示,答案几乎相同。如果仅使用变量名,则会使用相同的名称自动创建属性。

答案 1 :(得分:3)

您可以序列化匿名类型:

var json = JsonConvert.SerializeObject(new { Phone, Password, Location});

See a live demo on rextester.