2015-10-14 112 views
1

JSON响应字符串我收到以下类型的JSON从Web服务响应:查找和替换在净

{"students":[{"studentID":"123456789","section":"S","RefId":"  ","pastScore":"99952","currentScore":"99952","inquiryAllowed":true},{"studentID":"223456789","section":"R","RefId":"  ,"pastScore":"152","currentScore":"952","inquiryAllowed":true},{"studentID":"323456789","section":"T","RefId":"  ,"pastScore":"4582","currentScore":"5952","inquiryAllowed":true},],"schoolName":"WatsonPrimarySchool"} 

我需要屏蔽studentID,pastScore,currentScore和schoolName。输出将如下所示:

{"students":[{"studentID":"$$$$$$$$","section":"S","RefId":"  ","pastScore":"$$$$$","currentScore":"$$$$$","inquiryAllowed":true},{"studentID":"$$$$$$$$$","section":"R","RefId":"  ,"pastScore":"$$$","currentScore":"$$$","inquiryAllowed":true},{"studentID":"$$$$$$$$$","section":"T","RefId":"  ,"pastScore":"$$$$","currentScore":"$$$$","inquiryAllowed":true},],"schoolName":"$$$$$$$$$$$$$$$$$$$"} 

schoolName只会发生一次,其余的可以是多个。

我试过使用StringBuilder,但由于值的动态性质,它没有成功。有人可以建议一个正则表达式解决方案吗?

+1

反序列化一个对象,并在吸气这些属性返回'“$$$$$$”'或任何 – DGibbs

+0

转到http://json2csharp.com/粘贴您的JSON格式,它会生成类。使用Json.Net将类转换为JSON,反之亦然。 – Chandru

+0

@DGibbs - 我同意将响应转换为类并在getter中屏蔽值是一个很好的过程,但由于需要特殊要求,需要直接处理JSON字符串。 – Vguy

回答

1

使用JSON.Net到JSON转换为一类,面膜要屏蔽性能,并再次使用JSON.Net生成JSON的屏蔽值

您可以使用JSON任何其他库同时,JSON.Net只是使用最简单的,我知道 - 检查许可条件也

0

您可以使用Json.Net和LINQ

var propsToMask = new HashSet<string>(new[] { "studentID", "pastScore", "currentScore", "schoolName" }); 
var jObj = JObject.Parse(json); 

foreach(var p in jObj.Descendants() 
        .OfType<JProperty>() 
        .Where(p => propsToMask.Contains(p.Name))) 
{ 
    p.Value = "$$$$$$"; 
} 

var newJsonStr = jObj.ToString(); 
+0

谢谢,但我不允许使用外部组件,所以不能使用JSON.Net。是否有一个.Net原生类可以完成相同的工作? – Vguy

-1

@DGibbs是一个很好的提示。 但是,如果你决定去正则表达式:

Regex.Replace(jsonInput, "((studentID|pastScore|currentScore|currentScore)\":\")(.+?)\"", "$1\$\$\$\"") 
+0

我用你的建议。为了克服“无法识别的转义序列”错误做了一些小改动。输出符合要求。 – Vguy

0

的解决方案:

  1. 将字符串到对象,然后将其转换成任何你想要的。
  2. 做它直接使用StringBuilder

第一个解决方案,采用JSON.NET:这里是步骤:

  1. 你应该重新检查你的JSON,消除不需要的空间。如果您的JSON包含它们,如'studentID',则无法正确解析它。下面是我做的:

    { 
    'students' : [{ 
         'studentID' : '123456789', 
         'section' : 'S', 
         'RefId' : '  ', 
         'pastScore' : '99952', 
         'currentScore' : '99952', 
         'inquiryAllowed' : true 
        }, { 
         'studentID' : '223456789', 
         'section' : 'R', 
         'RefId' : '  ', 
         'pastScore' : '152', 
         'currentScore' : '952', 
         'inquiryAllowed' : true 
        }, { 
         'studentID' : '323456789 ', 
         'section' : 'T', 
         'RefId' : '', 
         'pastScore' : '4582', 
         'currentScore' : '5952', 
         'inquiryAllowed' : true 
        } 
    ], 
    'schoolName' : 'WatsonPrimarySchool' 
    } 
    
  2. 使用Nuget Packages到Json.NET库添加到您的项目。 NewtonSoft

  3. 创建2个类来保存数据:

Student.cs

public class Student 
{ 
    public string StudentId { get; set; } 
    public string Section { get; set; } 
    public string RefId { get; set; } 
    public string PastScore { get; set; } 
    public string CurrentScore { get; set; } 
    public bool InquiryAllowed { get; set; } 
} 

School.cs

public class School 
{ 
    public List<Student> Students { get; set; } 
    public string SchoolName { get; set; } 
} 
  • 主程序。

    string json = "Your JSON string"; 
    
        // Convert JSON string to object 
        var school = JsonConvert.DeserializeObject<School>(json); 
    
        // Mask it as you want 
        foreach (var student in school.Students) 
        { 
         student.StudentId = "$$$$$$$$"; 
         student.PastScore = "$$$$$$$$"; 
         student.CurrentScore = "$$$$$$$$"; 
        } 
        school.SchoolName = "$$$$$$$$"; 
    
        // Convert object back to string 
        string masked = JsonConvert.SerializeObject(school); 
    
        // Show it 
        Console.WriteLine(masked); 
    
        Console.ReadLine(); 
    
  • 解决方法二:使用StringBuilder

    首先,你必须检查您的JSON字符串,以确保它有一个正确的格式。我在上面的第一步中做了。出于测试原因,我将所有双引号替换为单引号。

    这是程序,使用StringBuilder。我在那里发表评论。如果您不明白,请随时提问。

    static void Main(string[] args) 
    { 
        string json = "{'students':[{'studentID':'123456789','section':'S','RefId':'  ','pastScore':'99952','currentScore':'99952','inquiryAllowed':true},{'studentID':'223456789','section':'R','RefId':'  ','pastScore':'152','currentScore':'952','inquiryAllowed':true},{'studentID':'323456789 ','section':'T','RefId':'','pastScore':'4582','currentScore':'5952','inquiryAllowed':true}],'schoolName':'WatsonPrimarySchool'}"; 
        var builder = new StringBuilder(); 
    
        // The cursor 
        int start = 0; 
    
        while (true) 
        { 
         bool notFoundStudentId = false; 
         bool notFoundPastScore = false; 
         bool notFoundCurrentScore = false; 
    
         // Student ID 
         int index = json.IndexOf("'studentID'", start, StringComparison.Ordinal); 
         if (index > 0) 
         { 
          // Append everything from the starting point to the beginning of 'studentID' 
          builder.Append(json, start, index - start); 
    
          // Mask it 
          builder.Append("'studentID':'$$$$$$'"); 
    
          // Move the starting point to the comma after 'studentID' value 
          start = json.IndexOf(',', index); 
         } 
         else 
         { 
          notFoundStudentId = true; 
         } 
    
         // Past score 
         index = json.IndexOf("'pastScore'", start, StringComparison.Ordinal); 
         if (index > 0) 
         { 
          builder.Append(json, start, index - start); 
          builder.Append("'pastScore':'$$$$$$'"); 
          start = json.IndexOf(',', index); 
         } 
         else 
         { 
          notFoundPastScore = true; 
         } 
    
         // Current Score 
         index = json.IndexOf("'currentScore'", start, StringComparison.Ordinal); 
         if (index > 0) 
         { 
          builder.Append(json, start, index - start); 
          builder.Append("'currentScore':'$$$$$$'"); 
          start = json.IndexOf(',', index); 
         } 
         else 
         { 
          notFoundCurrentScore = true; 
         } 
    
         // Found nothing? It's time for schoolName 
         if (notFoundStudentId && notFoundPastScore && notFoundCurrentScore) 
         { 
          index = json.IndexOf("'schoolName'", start, StringComparison.Ordinal); 
          builder.Append(json, start, index - start); 
          builder.Append("'schoolName':'$$$$$$'}"); 
    
          // End the loop 
          break; 
         } 
        } 
    
        // Display 
        Console.WriteLine(builder.ToString()); 
        Console.ReadLine(); 
    } 
    
    +0

    感谢您的时间,但正如我已经提到的,由于一个特殊的要求,需要直接处理JSON字符串。 – Vguy

    +0

    好吧,我会直接做:) – AnhTriet

    +0

    当然。我将尝试验证Regex解决方案和字符串生成器解决方案的性能和更新。 – Vguy