I wrote a PowerShell script that inserts NewtonSoft JSON annotation above each line.
Starting file:
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; }
}
Result file that isn't correct:
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
The script:
$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"
Result file that I want to be:
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
Questions:
Why won't it add
$FileOriginal[$i].Split()[2]to my JSON PropertyName?Answer (editied): I just realized that my line contains multiple blanks so for now I can get value like
$FileOriginal[$i].Split()[10].How to replace my array
$lines[3]element and to capitalize first letter? (public string clientID->public string ClientID)- How to properly format my txt output to be exactly the same formatted as startingFile?