1

I need help storing text from a parsed JSON message into variables based on keywords. What I mean by this is, I have a JSON message that I have parsed once, and within that message, it returns things like:

Name: Kobe Bryant<br/>
Company: Lakers<br/>
Email: kobe@lakers.com<br/>
etc.

I want to be able to look at this block of test, see that it says "Name: Kobe Bryant," and store Kobe Bryant into a string variable called "name" and so on. How can I handle this?

public class ParseTest {
    public static void main(String[] args) throws Exception {

        String name;
        String company;
        String email;
        String phoneNumber;
        String projectType;
        String contactBy;
        String timeFrame;
        String message;

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

        MainParser mp = mapper.readValue(new File("/Users/kane/VersionControl/LambdaTest/src/InfoBox.txt"), MainParser.class);

        if ("blah".equals(mp.getTopicArn())) {
            //Send to proposal table
            System.out.println(mp.getSubject());
            System.out.println(mp.getMessage());
        } else if ("blah blah".equals(mp.getTopicArn())) {
            //Send to infoBox table
            System.out.println(mp.getMessage());
        }
    }
}

The JSON that I'm parsing is:

{
 "Subject" : "Proposal Request (sent Wed May 22 2019 14:47:49 GMT-0400 (Eastern Daylight Time))",
 "Message" : "Name: Kobe Bryant\nCompany: Lakers\nEmail: kobe@lakers.com"
}

Here's the POJO class:

private String Subject;
private String Message;

public String getSubject() {
    return Subject;
}

public void setSubject(String subject) {
    Subject = subject;
}

public String getMessage() {
    return Message;
}

public void setMessage(String message) {
    Message = message;
}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
Kane
  • 15
  • 3
  • `"Message"` key does not contains valid `JSON` object. But just a text which looks like this: `"Name: Kobe Bryant\nCompany: Lakers\nEmail: kobe@lakers.com"`. So, every `key-value` pair is separated by new line. Could you confirm that? – Michał Ziober May 24 '19 at 21:30
  • @MichałZiober Sorry for such a late response, but yes, you are correct. Every line is separated by new line. – Kane May 28 '19 at 20:47

1 Answers1

0

You have a JSON payload where one of values contains data in key:value pairs split by new line \n. We need to create two POJO classes: Message for root JSON and Person - internal person data. These two classes could look like this:

class Message {

    private String subject;
    private String message;

    // getters, setters, toString
}

class Person {

    private String name;
    private String company;
    private String email;

    // ... more properties

    // getters, setters, toString
}

We can parse your JSON payload as below:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import java.io.File;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);

        Message message = mapper.readValue(jsonFile, Message.class);
        String[] lines = message.getMessage().split("\n");

        Map<String, String> properties = Stream.of(lines)
                .map(i -> i.split(":"))
                .filter(i -> i.length == 2)
                .collect(Collectors.toMap(i -> i[0].trim(), i -> i[1].trim()));

        Person person = mapper.convertValue(properties, Person.class);
        System.out.println(person);
    }
}

Above example prints for your JSON payload:

Person{name='Kobe Bryant', company='Lakers', email='kobe@lakers.com'}

As you can see, we created Map from internal data and used convertValue method to convert Map to Person class.

See also:

  1. Java 8 – Convert List to Map
  2. How to deserialize a Map into POJO?
  3. How to serialize to java.util.List and java.util.Map with Jackson
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146