jyriand
jyriand

Reputation: 2534

text data into JSON object in Java

I have a text file that contains letters and numbers. This letter-number combination holds information about a user. For example: "P555636477JohnDoeEA 55687878 9789899 2899298" First letter can be either "P/G/S" meaning Premium, Gold or Simple. Follows his telephone number and name. Two letters E and A mean native language(English) and nationality (American). Then follows his other telephone numbers, that he has registered. There might be more than 3 numbers. My question is: what is the best method to parse this information into JSON object? Im thinking about using regex and StringBuilder, but Im not sure how to approach those telephone numbers at the end...

It should look something like this:

{ "membership":   "Premium", 
  "telephone":    "555636477", 
  "firstName":    "John",
  "lastName":     "Doe",
  "otherNumbers": [
                   {"number:"55687878"},
                   {"number":"9789899"},
                   {"number":"2899298"}
                  ]
}

Upvotes: 0

Views: 151

Answers (2)

tbraun89
tbraun89

Reputation: 2234

Are this last numbers seperated through sprace characters? If so, you can use the split method, to get an array of Strings.

Then you have to use a RegEx for the first entry, all others are your telephone numbers.

The array would look like:

["P555636477JohnDoeEA", "55687878", "9789899", "2899298"]

Then you could use json-lib or an other library to get your data to JSON.

Upvotes: 2

beerbajay
beerbajay

Reputation: 20300

Easiest would be to make a object which holds this information, parse your text file with a regexes, set the appropriate properties of the object and then serialize it with jackson.

Upvotes: 1

Related Questions