Thousands of prosecutions for alleged fare evasion brought by train companies are set to be declared void after a judge’s ruling.