1

In my Java project I am constantly getting a string input such as "{type=01010201, capacity=700, auth_method=01, auth_no=090713}"

When I am trying to parse this string like below, it seems to fail

JsonObject tot_payload = null;
try {
    tot_payload = new JsonObject(obj.getString("data"));
} catch (Exception e) {
    log.error("record in json parsing error");
}

I understand that this is due to the fact that I am missing the spaces for the string. My application receives a variety of different strings like this and I was wondering if there would be any efficient way of turning such string into a json object.

10
  • But where is your data atrribute? As far as I see, your input has type, capacity, auth_method, auth_no, but you're trying to fetch the key that is not inside this object. Commented Apr 26, 2022 at 7:26
  • 1
    I think "tot_payload" object must be string and tot_payload=obj.getString("data"); Commented Apr 26, 2022 at 7:27
  • 1
    can you add obj variable value Commented Apr 26, 2022 at 7:29
  • 3
    Contrary to your assumption, the JSON format does not require spaces, but it expects colons instead of equal signs. Commented Apr 26, 2022 at 7:53
  • 1
    @mutantkeyboard The value that I mentioned is the result I get from obj.getString("data"), It is a json inside a json Commented Apr 26, 2022 at 11:47

1 Answer 1

1

Assuming that it is org.json.JSONObject, preprocessing your input into actual JSON format should solve the problem:

import static org.assertj.core.api.Assertions.assertThat;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;

class JSONObjectLT {
    
    @Test
    void parseString() throws JSONException {
        
        final String input = "{type=01010201, capacity=700, auth_method=01, auth_no=090713}";
        
        // only works if keys/values do not contain equal signs
        final String preprocessed = input.replace('=', ':');
        final JSONObject json = new JSONObject(preprocessed);

        assertThat(json.getString("type")).isEqualTo("01010201");
        assertThat(json.getInt("capacity")).isEqualTo(700);
    }
}

Maven dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-json-org</artifactId>
    <version>2.13.2</version>
</dependency>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.