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

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.

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.

Related

Parsing json list when there is an exceptional objects as well using Retrofit2

Previously I was receiving the response like this:
I was parsing it like: Call<List<MyObject>> getList();
But now there are some new elements were added and the response changed to:
How to parse this object now? I searched my could not find any solutions.
This is how I am setting up my client.
This is the json object which i recieve as a response:
{"map":{"01":{"F":".","E":".","D":null,"C":null,"B":".","A":"."},"02":{"F":".","E":".","D":null,"C":null,"B":"Z","A":"."},"03":{"F":"A","E":"A","D":null,"C":null,"B":"A","A":"A"},"board":false,"type":{"num":"TT334","board":"WW","date":"31MAR","route":"AWETSW","pcount":""}}}
I dont
There are two potential solutions:
You create a DTO. Gson will ignore fields you don't map in your dto. Your json doesn't use a list it is entirely objects.
You manually parse the json using Gson's JsonReader
You can use a mixture of DTOs and manual parsing. I have done this for large json datasets and inconsistent datasets.

What is the best way to parse JsonObject containing just one enormous JsonObject (Gson)

I have a Json of this type :
{
"4f958ef28ecd651095af6ab6": {
enormous JsonObject
}
}
the "4f958ef28ecd651095af6ab6" is different each time (but I know what it will be as it is a parameter of my api call), it corresponds to the id of the following object. I have a Gson-configured model to parse the enormous JsonObject.
My question is : is it performant to use simply
new JSONObject(jsonresponse).getJSONObject("4f958ef28ecd651095af6ab6")
and parse with Gson from there ?
Is there a better way to do so ?
I guess the real question would be, what does "new JSONObject(String)" realy do ?
Thanks
What you are doing is:
You load all the Json string into the phone memory (memory issue + long time to load entirely)
You create a big JSONObject (same issues) in order to have access to each key.
You write few code but this is not the most performant solution.
To minimized the memory impact and accelerate the operation of objects' creation, you can use Gson in stream mode.
By directly read the input stream, you avoid to load too much data and you can directly start to populate your object piece by piece.
And about the JSONObject, it will mostly check if your json string is correct (or it will throw a JsonException) and it will let you look into the object when you search for a key and its value.
I would recommend use hybrid (native and gson) since i am not sure how to get unknown jsonobject with GSON.
You need to get your response as a JSONArray, then itarete for each JSONObject. You can experiment parsing code as trying. Please check JSONArray.getJSONObject(int index) method. Then we can use GSON to get our data model to get known attributes.
If you can post complete json data, we can give it chance to parse together.

Unable to parse JSON using Retrofit

I am using Retrofit to hit an api. I need to get both Json and header response. So my interface method is like this. So in Response type Object I get response header from response.getHeaders(). But when I try to get the json response from response.getBody(), I don't get a proper response. I need help in fetching and parsing the json response from the Response object :-(
#GET("/api/hello/categories")
retrofit.client.Response getData();
getBody() doesn't return a String directly, you'll have to convert it yourself if you don't want to user Retrofit's built converters.
This link should be a simple way to grab the String from the response, and you can parse it accordingly.

Rest Client with AndroidAnnotations - "no suitable HttpMessageConverter..."

I want to send POST request to server. I have to pass JSON object as a parameter, and get JSON as a response, but I am getting this error:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.package.Response] and content type [application/octet-stream]
Code
Sending request:
#RestService
RestClient restClient;
...
String json = "{\"param\":3}";
restClient.getRestTemplate().getMessageConverters().add(new GsonHttpMessageConverter());
Response res = restClient.send(json);
RestClient
#Rest("http://my-url.com")
public interface RestClient
{
#Post("/something/")
Response send(String json);
RestTemplate getRestTemplate();
void setRestTemplate(RestTemplate restTemplate);
}
I'm using these JAR files:
spring-android-rest-template-1.0.0.RC1
spring-android-core-1.0.0.RC1
spring-android-auth-1.0.0.RC1
gson-2.2.2
What I'm doing wrong? When I change send parameter to JSONObject I am getting the same error.
Btw. AA docs are really enigmatic - can I use Gson anyway? Or should I use Jackson? Which file do I need to include then?
Thanks for any help!
You can use RestTemplate with either Gson or Jackson.
Gson is fine and easier to use of you have small json data set. Jackson is more suitable if you have a complex / deep json tree, because Gson creates a lot of temporary objects which leads to stop the world GCs.
The error here says that it cannot find a HttpMessageConverter able to parse application/octet-stream.
If you look at the sources for GsonHttpMessageConverter, you'll notice that it only supports the mimetype application/json.
This means you have two options :
Either return the application/json mimetype from your content, which would seam quite appropriate
Or just change the supported media types on GsonHttpMessageConverter :
String json = "{\"param\":3}";
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setSupportedMediaTypes(new MediaType("application", "octet-stream", Charset.forName("UTF-8")));
restClient.getRestTemplate().getMessageConverters().add(converter);
Response res = restClient.send(json);
I just had this problem. After several hours I realised that the class I was passing in to the RestTemplate.postForObject call had Date variables. You need to make sure it only contains simple data types. Hope this helps someone else!
I have to modify it little to work:
final List<MediaType> list = new ArrayList<>();
list.addAll(converter.getSupportedMediaTypes());
list.add(MediaType.APPLICATION_OCTET_STREAM);
converter.setSupportedMediaTypes(list);

How to parse a complex object with ksoap?

I use ksoap to connect to a soap web service. And get a Soapobject in return. How would I parse this complex soapobject.
My problem is that a SoapObject returns an object for getProperty, this can be a leaf or a node in the tree. I have a complex resultobject that consists of some ints and strings and a list of complex objects. I now somehow have to decide if the property is a leaf or another complex object that can be parsed as an SoapObject.
Is there an example on how to parse this?
You could find this tutorial useful on handling complex objects in KSOAP with Android:
Complex objects tutorial with sample code
Hope this helps
I think, you can use this android web service client open source tool.
Where you needn't parse the complex response object. Its just like call a method of a service.
say, for a service say ComplexRespService with param ComplexResponse you have to just write :
ComplexRespService service = new ComplexRespService ();
CoplextRespPort port = service.getPort();
ComplexResponse resp = port.getResponse ( "someRequest");
In this way, It support the complex request/response. This tool can generate "ws client stub" from just the wsdl file.
I have added a bit about parsing a complex pojo array on the wiki now. Check it out at
http://code.google.com/p/ksoap2-android/wiki/CodingTipsAndTricks

Categories

Resources