我编写了一个PowerShell脚本,在每行上面插入了NewtonSoft JSON注释。
开始文件:
public class Rootobject
{
public string clientID { get; set; }
public string bankID { get; set; }
public string applicationID { get; set; }
//(...)
public string appName { get; set; }
public GeneralData loanDataRequest { get; set; }
}
public class Roles
{
public string role1 { get; set; }
public string otherParty1 { get; set; }
}
结果文件不正确:
public class Rootobject
{
[JsonProperty(PropertyName = "")]
public string clientID { get; set; }
[JsonProperty(PropertyName = "")]
public string bankID { get; set; }
[JsonProperty(PropertyName = "")]
public string applicationID { get; set; }
...
}
//other properties are exluded due to simplicity of the code
剧本:
$FileName = "E:\startingFile.txt"
$FileOriginal = Get-Content $FileName
$lines = (Get-Content E:\startingFile.txt)
#trim lines
$newcontent = foreach ($line in $lines) {
$line.Trim()
}
for ($i = 0; $i -lt $FileOriginal.Length; $i++) {
if ($FileOriginal[$i] -like "*public*" -and $FileOriginal[$i] -notlike "*class*") {
# insert your line before this line and not insert if line contains '{','}'
$FileOriginal[$i] -replace 'public', '`npublic'
$FileOriginal[$i] -replace '{', '`n{'
$NewFileContent += "`n[JsonProperty(PropertyName = """ + $FileOriginal[$i].Split()[2] + """)]"
}
$NewFileContent += $FileOriginal[$i]
}
$NewFileContent | Out-File "E:\resultFile.txt"
我想成为的结果文件:
public class Rootobject
{
[JsonProperty(PropertyName = "clientID ")]
public string ClientID { get; set; }
[JsonProperty(PropertyName = "bankID ")]
public string BankID { get; set; }
[JsonProperty(PropertyName = "applicationID ")]
public string ApplicationID { get; set; }
...
}
//other properties are exluded due to simplicity of the code
问题:
为什么不将$FileOriginal[$i].Split()[2]
添加到我的JSON PropertyName中?
答案(编辑):我刚刚意识到我的行包含多个空格,所以现在我可以得到像$FileOriginal[$i].Split()[10]
这样的值。
如何替换我的数组$lines[3]
元素并将首字母大写? (public string clientID
- > public string ClientID
)
答案 0 :(得分:1)
不要为将元素插入数组或构建输出字符串而烦恼。只需将新行插入输出流即可。此外,如果您希望保留缩进:不要修剪前导空格。
Get-Content 'E:\startingFile.txt' | ForEach-Object {
if ($_ -like '*public*' -and $_ -notlike '*class*') {
if ($_ -match '^(\s*)(public\s+\w+\s+)(\w)(\w*)(.*)') {
'{0}[JsonProperty(PropertyName = "{1}{2}")]' -f $matches[1,3,4]
$_ = '{0}{1}{2}{3}{4}' -f $matches[1], $matches[2], $matches[3].ToUpper(), $matches[4], $matches[5]
}
}
$_
} | Set-Content 'E:\resultFile.txt'