Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

android - Is there any way to convert JSONP format to JSON?

I am trying to parse a response from server and i am new to this topic, Unfortunately it is in JSONP format. I don't know how to parse JSONP format, when i tried with JSON Parser it is returning null value. Can anyone please help me in doing this...

Thanks in Advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

JSONP is just JSON wrapped in a JavaScript function call. For instance, something like:

callback({"status":"success", "someVar":1});

So you have a couple of options. If you are using a WebView you can define a function called callback in JavaScript and then just call eval() on the JSONP data. This will invoke the callback function, passing it the parsed JSON object (the eval() does the parsing for you).

Or, if you have the JSONP string in your Java code, the simplest option is probably to extract out the JSON substring, like:

String json = jsonp.substring(jsonp.indexOf("(") + 1, jsonp.lastIndexOf(")"));

That will strip off callback( and );, leaving you with just {"status":"success", "someVar":1}, which should then parse with any standard JSON parser.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...