Converting from HttpURLConnection TO Retrofit2 Issues - java

I'm upgrading some legacy Android / Java code that pulls in data from a server. The legacy code uses HttpURLConnection and pulls in a inputStream and converts it to a GZipInputStream. The result is then converted to a JSONObject. Then the data is parsed manually. This all works fine, meaning valid json is returned as it starts with '{'
I'm trying to updgrade this code using Retrofit2 and the GsonConverterFactory so I can auto map the json to Classes.
I'm getting an error: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
This tells me that the data is coming in as a string and not a JSON object.
NOTE: I'm sending the same headers and query parameters for both my legacy code and new Retrofit implementation --- but different result -- can't figure out why.

The issue was that the server was expecting all of my query parameters to be in one field and the field named "Object" and in a json format i.e: Object={"field1":"fieldOneValue","field2":"fieldTwoValue"} AND had to be Url Uncoded Format:
#FormUrlEncoded
#POST("testing/myapi.api")
Observable<MyClass> getMyApiData(#Url String url, #Field("Object") String object);

Related

Does Gson’s fromJSON have a parsing limit on the string parameter?

I’m using GSON to convert a JSON string stored in our DB to our corresponding object class.
String configData = dbCall.fetchPublishedData(dbURL); //returns JSON string
Gson gson = new Gson();
publishDataObject = gson.fromJson(configData, PublishedDataVO.class);
For the most part, this is working, except for one particular row in our DB that is failing with an exception from the GSON parser. All of our rows in the DB are created with the same tool and have the same data structure, the only difference for this one row is that it holds A LOT of data in its JSON string. When I try to retrieve this data and transform it into our class object, I am getting the following error:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 4001 path...
The size of the data string in this row is the only difference with the other row's strings. I even took the JSON string and formatted it to see if it is a valid JSON string, and it doesn't show errors. Does GSON have a limit on the input string size for its fromJSON method?

Listing the parameters in a node using RESTassured library with Java

The webservice: http://services.groupkt.com/country/search?text=lands has 16 records returned from a GET request. In the records, there is a parameter called 'name'. So, there are 16 names and each name has a unique value (country). My intention is to list all the 16 values of the 'name'parameter using java and the RESTassured library. I tried this:
Response response = RestAssured.get("http://services.groupkt.com/country/search?text=lands").andReturn();
String json = response.getBody().asString();
JsonPath jp = new JsonPath(json);
List<String> ls = from(response).getList("RestResponse.result.name");// The 'from' text displays an error
An error was seen on the 'from' text and it says: The method from(String) in the type RestTest is not applicable for the arguments (Response). I am not sure how to rectify this. Is there a simple way to create a list of all the values of the 'name' parameter?
Try replacing from(response) to from(jp). That should take care of the error you are getting.
The Response class (which is what the get() method returns) also supports jsonPath, so you could also refactor it to something like this:
List names= get("http://services.groupkt.com/country/search?text=lands").jsonPath().getList("RestResponse.result.name");

Can not deserialize instance of java.sql.Timestamp out of VALUE_NUMBER_FLOAT token

I have a RESTful API on Jersey 2.17 with Jackson on JDK8. It is JSON style API. This API accepts a Java object, it has this field:
#JsonProperty("processEndTime")
public Timestamp getRunDate() {
return runDate;
}
#JsonProperty("processEndTime")
public void setRunDate(Timestamp runDate) {
this.runDate = runDate;
}
Now when I submit a small number, it works perfectly like this:
"processEndTime" : 1434989360,
But it fails when the number is big one, like this:
"processEndTime" : 1434989360380,
The most weird thing is that I had a Jmeter test case, it sent the exact the same big number, it can pass without any issues. I can verify this number on the server side and confirmed it is correctly passed.
The full error message is:
Can not deserialize instance of java.sql.Timestamp out of VALUE_NUMBER_FLOAT token at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream#23117fbd; line: 1, column: 562] (through reference chain: com.abc.api.dto.MyClassA["processEndTime"])
Any suggestions?
I figure out the issue:
I did some converting in the request data:
JSONObject analysis = new JSONObject(templateAnalysis3);
data = analysis.toString();
this toString function will convert long number to E format:
1434989360380 -> 1.43498936038E12
This E format is not supported and caused this failure.
I fixed it by using templateAnalysis3 directly:
data = templateAnalysis3;

Mongodb- java function com.mongodb.util.JSON.parse()

I am now using java method com.mongodb.util.JSON.parse(param) to convert my json string to a DBObject.I find that, in most cases , for example , when the key in the json string is simple type like string or int ,it can be used by both JSON.parse() method and terminal.
For example:
json string:{'times':8}
Both JSON.parse({'times':8}) and db.collection.find({'times':8}) in terminal can work correctly.
But when I do a query on ISODate or _id,things become different:
json string 1 :{'createDate':ISODate('2013-10-21T06:39:16.692Z')}
json strign 2: {'createDate':{'$date':'2013-10-21T06:39:16.692Z'}}
json string 1 can work correctly in terminal but cannot be parsed by JSON.parse() method.
On the contrary , json string 2 can be parsed by JSON.parse() method but cannot be used in terminal.
The same thing happened in _id.
json string 3:{'_id':ObjectId('1231daf213432414321431')}
json string 4:{'_id':{'$oid':'fadf234234sdfadfasdfa12'}}
json string 3 can work correctly in terminal but cannot be parsed by JSON.parse() method.
On the contrary , json string 4 can be parsed by JSON.parse() method but cannot be used in terminal.
I don't know the reason of these differences.
The constructors you are using in the Mongo Shell are JavaScript code that is obviously not part of strict JSON that you want to parse in your Java application. The point to be criticized here is rather that the shell does not support something like '$date' (as I have just tested myself as well).
This is for example discussed here.

json cause crash - Android

I'm using Json with PHP to connect my android app with a remote mySql db.
but for some reason the JSON parser returns and error saying there's a problem with the json string.
The json string is: {"success":1,"message":"sit created."}
the error is: Error parsing data org.json.JSONException: A JSONObject text must begin with '{' at character 1 of {"success":1,"message":"sit created."}
Can anyone tell me what the problem is, I can't figure it out.

Categories