0

I have a long String, which is a json files contents. Somewhere in this String, it contains the following: "totalWinAmount":100

To find and return this value, I'm currently doing this:

int totalWinAmountIndex = line.lastIndexOf("totalWinAmount");
String resultTotalWinAmount = line.substring(totalWinAmountIndex + 16, totalWinAmountIndex + 19);

This works, resultTotalWinAmount is correctly set to 100, but I'm curious if this is the best practise for a situation like this, whether this is actually awful coding, or if there's a better way of doing it?

James
  • 749
  • 1
  • 9
  • 22
  • 2
    You could use regex. – Steve Smith Sep 27 '18 at 10:47
  • Really depends on what this is for, where it's being used etc. In a professional business environment I'd use a JSON library to parse the entire thing into an object representation and then get the value from there. In a small tool I hack for myself at home I'd probably do exactly what you did. – Max Vollmer Sep 27 '18 at 10:49
  • If it's always in the same place, and `totalWinAmount` remains as is, there is no real issue with what you've done. Except maybe use a constant in place of hardcoding `16` and `19`. But perhaps consider a proper JSON parser. – achAmháin Sep 27 '18 at 10:50

2 Answers2

1

You can use RegExp: "\s*totalWinAmount\s*"\s*:\s*(?<totalWinAmount>\d*)

This is Demo at regex101.com

This is the most simpliest way to get couple of values (I think that using json converter is overhead for this reason). But if you want to find more values, then definitely, you have to use json converter (e.g. Jackson).

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

You could also try to extract the value with the use of regex. Something like this should work:

resultTotalWinAmount = str.split(".*\"totalWinAmount\"\\s*:\\s*")[1].split("\\D+")[0];

That's a bit messy, but works without additional libraries.

However, I agree with Sun. For proper analysis of json you should always use something like Jackson or GSON.

lema
  • 344
  • 7
  • 15