0

Hi so I have encoded JSON from PHP and it comes out like this :

{"ticket":[
{"ticket":[{"a":"10.00","b":"1.00","c":"1.00","d":"abcde","f":"7"},
{"ticket":[{"a":"10.00","b":"1.00","c":"1.00","d":"abcde","f":"7"}
]}


    object      {1}
    ticket      [2]
            0       {6}
a   :   10.00
b   :   1.00
c   :   1.00
d   :   abcde
e   :   7

        1       {6}
a   :   10.00
b   :   1.00
c   :   1.00
d   :   abcde
e   :   7

when i open this in java the whole thing comes across as one JSONObject which I break into two JSONArrays the first contains the work ticket and then second contains

    {"ticket":[{"a":"10.00","b":"1.00","c":"1.00","d":"abcde","f":"7"},
    {"ticket":[{"a":"10.00","b":"1.00","c":"1.00","d":"abcde","f":"7"}

The second JSONArray as you expect has a length of 2 and can be broken down into the two lines above (each as a string) but is there a way i can get the data out of the string without doing stuff on it /tokenising it looking for the values of a,b,c ...etc ?

2 Answers 2

2

Your provided JSON is flawed. It's missing the closing ] on the second and third ticket key.

Also, if possible you should change the names, 3 ticket keys is highly confusing when you're searching for errors within the JSON object. Based on that I am not sure how your JSON is supposed to look like.

You should use the provided JSONObject functions to access the values. They are easy to use and you don't need to create intermediate variables.

Assuming your JSON looks like this and is stored within a JSONObject variable called json:

{ "tickets":
  [
    { "tickets2": [{"a": 1, "b": 2, ...}] },
    { "tickets3": [{"a": 3, "b": 4, ...}] }
  ]
}

It would be possible to access the values like this:

json.getJSONArray("tickets").getJSONArray("tickets2").getInt("a");  // = 1

If you just want to check if the values are available, use the isNull function.

if (json.getJSONArray("tickets").getJSONArray("tickets2").isNull("a")) {
  //a is not available
}

Keep in mind that get* functions throw JSONException when the desired key is not available and isNull will return true for a value of null as well.

Sign up to request clarification or add additional context in comments.

Comments

0

Try GSON library which can convert a JSON string to an equivalent Java object.

https://sites.google.com/site/gson/gson-user-guide

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.