Skip to content
Advertisement

Converting line and column coordinate to a caret position for a JSON debugger

I am building a small Java utility (using Jackson) to catch errors in Java files, and one part of it is a text area, in which you might paste some JSON context and it will tell you the line and column where it’s found it:

enter image description here

I am using the error message to take out the line and column as a string and print it out in the interface for someone using it.

This is the JSON sample I’m working with, and there is an intentional error beside “age”, where it’s missing a colon:

JavaScript

What I want to do is also highlight the problematic area in a cyan color, and for that purpose, I have this code for the button that validates what’s inserted in the text area:

JavaScript

The “addHighlight” method works with a start range, end range and a color, which didn’t become apparent to me immediately, thinking I had to get the reference line based on the column number. Some split functions to extract the numbers, I assigned 11 (in screenshot) to a caret value, not realizing that it only counts character positions from the beginning of the string and represents the end point of the range.

For reference, this is the class that does the work behind the scenes, and the error handling at the bottom is about extracting the line and column numbers. For the record, “x” is the error message that would generate out of an invalid file.

JavaScript

Screenshot for what the interface currently looks like: enter image description here

Long story short – how do I turn the coordinates Line 4, Col 11 into a caret value (e.g. it’s value 189, for the sake of argument) that I can use to get the highlighter to work properly. Some kind of custom parsing formula might be possible, but in general, is that even possible to do?

Advertisement

Answer

how do I turn the coordinates Line 4, Col 11 into a caret value (e.g. it’s value 189,

Check out: Text Utilities for methods that might be helpful when working with text components. It has methods like:

  1. centerLineInScrollPane
  2. getColumnAtCaret
  3. getLineAtCaret
  4. getLines
  5. gotoStartOfLine
  6. gotoFirstWordOnLine
  7. getWrappedLines

In particular the gotoStartOfLine() method contains code you can modify to get the offset of the specified row/column.offset.

The basic code would be:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement