I'm getting many JSON objects through a web service and at times the json object is malformed.
I wanted to check the if the json is valid before processing it.
So i worte
JsonElement jsonData = parser.parse(attacheddataattribute);
if(jsonData.isJsonObject())
{
//then only process
}
Not also its throwing a
com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 8432 at the parse method.
Is there any implemenation available to check for the JSON's validity.
That's your validation. No need to call any service.
If the method is throwing the MalformedJsonException it's a malformed JSON.
If you want you can wrap it in a method like
public boolean isValidJson(String json) {
try {
// parse json
return true;
} catch(MalformedJsonException e) {
return false;
}
}
I also had the MalformedJsonException crash but in my case I needed to add a catch block with Throwable:
fun jsonToList(value: String?): MutableList<String> {
var objects: Array<String> = emptyArray()
try {
objects = Gson().fromJson(value, Array<String>::class.java)
}catch (t: Throwable){
}finally {
return objects.toMutableList()
}
}
Related
I need to get parameters from DialogFlow to my Android app.
I tried using getQueryResult().getParameters().getFieldsMap()
but the result is the following.
{type=list_value {
values {
string_value: "pizza"
}
}
, ristorante=string_value: ""
}
I would like to get just the string value "pizza" and not the entire FieldMap.
I have already seen this topic, but it didn't help me, because I don't know what protobuf is and seems a bit complicated.
Is there a simple way to get a parameter's value?
I see two possibilities:
Try to access the Map values directly.
The getFieldsMap() method returns a java.util.Map class. You can try to retrieve the values by getting first a collection of Values, then iterate:
Collection colletion = <Detect_Intent_Object>.getQueryResult().getParameters().getFieldsMap().values():
for (iterable_type iterable_element : collection)
From my humble point of view the bucle is necesary because there could be more than one parameter.
Transform the protobuf response into a json and access the values.
Sample code:
import com.google.protobuf.util.JsonFormat;
String jsonString = JsonFormat.printToString(<Detect_Intent_Object>.getQueryResult().getParameters());
// Then use a json parser to obtain the values
import org.json.*;
JSONObject obj = new JSONObject(jsonString);
JSONArray jsonnames = obj.names();
Method names() will let you know the string names you want to access.
If you use Dialogflowv2
public String getParameter(GoogleCloudDialogflowV2WebhookRequest request, String parameterName) {
try {
GoogleCloudDialogflowV2QueryResult queryResult = request.getQueryResult();
Map<String, Object> parameters = queryResult.getParameters();
String parameter = (String) parameters.get(parameterName);
if(parameter != null && !parameter.equals("")) {
return parameter;
}
} catch (ClassCastException e) {
logger.error("Error");
}
return null;
}
If you use GoogleActions
public String getParameter(ActionRequest request, String parameterName) {
try {
Map<String, Object> parameters = request.getWebhookRequest().getQueryResult().getParameters();
String parameter = (String) parameters.get(parameterName);
if(parameter != null && !parameter.equals("")) {
return parameter;
}
} catch (ClassCastException e) {
logger.error("Error");
}
return null;
}
I am having some trouble with converting a Set of POJO's to a JSON string so I can store it in a database column. The conversion to JSON works as expected but when the conversion from JSON to a Set< Qualification > happens it always returns a LinkedHashSet<LinkedHashMap> which is causing issues.
The weird thing is that inside my converter the JSON string is converted successfully to a Set<Qualification>. When I debug in my IDE and step through the execution I can see that after it calls a deepCopy method in the MutableMutabilityPlan abstract class. At this point the data is of type LinkedHashSet<LinkedHashMap> and not Set<Qualification> from the conversion.
Here is my converter.
public class SetToStringConverter implements AttributeConverter<Set<Qualification>, String> {
private final ObjectMapper mapper = new ObjectMapper();
private final String errorMessage = "converter.invalid";
#Override
public String convertToDatabaseColumn(final Set<Qualification> items) {
try {
return mapper.writeValueAsString(items);
} catch (JsonProcessingException e) {
throw new ConverterFailureException(errorMessage);
}
}
#Override
public Set<Qualification> convertToEntityAttribute(final String data) {
try {
if (data != null) {
final Set<Qualification> s = mapper.readValue(data, new TypeReference<Set<Qualification>>() {});
return s; // Debugging here I have the correct type
}
return new HashSet<>();
} catch (IOException e) {
throw new ConverterFailureException(errorMessage);
}
}
}
I have done some research and have tried various approaches but the result is always the same.
Has anyone run into this issue before or can see anything wrong with my converter. Let me know if anything isn't clear so I can provide more information.
Thanks very much for the help.
I am using this library in order to get data from server. The data is decode in the server into JSONObject. The method I made will call the url and return the number of rows inside a mysql table.
The method is working however, I cannot return the value properly from my method:
ParseLevels.java
static public int countLevels() {
final int[] count = {0};
AndroidNetworking.get("https://example.com/gameLevels.php?option=count")
.setPriority(Priority.LOW)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
// responce is {count:20}
try {
count[0] = response.getInt("count"); // this is getting the value of 20
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("responce_app", String.valueOf(count[0]));
}
#Override
public void onError(ANError error) {
// handle error
Log.d("responce_app", String.valueOf(error)); //Logs out 20
}
});
return count[0]; // return always 0
}
When I call from my MainActivity
Log.d("responce_app", String.valueOf(ParseLevels.countLevels()));
the method returns always 0.
I understand that the return is fired before the jsonObject is fetched however, how can I wait for the method to fetch the jsonObject and after return the value?
In iOS I use something like:
static func getLevels(feedsArray: (levelsCount : [Int]) -> Void) {
}
how could convert this into Java?
How can I wait for the method to fetch the jsonObject and after return
the value?
Two options:
1. Do code inside onResponse method which want to execute according to result of request.
2. Create event listener using interface and implement it in countLevels method caller class to execute block of code when onResponse method execution done
You should look at the the Making Synchronous Request example from your library's README:
https://github.com/amitshekhariitbhu/Fast-Android-Networking
ANRequest request = AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.build();
ANResponse<List<User>> response = request.executeForParsed(new TypeToken<List<User>>() {});
if (response.isSuccess()) {
List<User> users = responseTwo.getResult();
} else {
//handle error
}
You would return your count in the response.isSuccess() conditional.
I'm implementing an Iterator and in order to deal with the Exceptions I'm using the following pattern: The actual work is done in the private hasNextPriv() method whereas the hasNext() method deals with the Exceptions. The reason for doing it this way is because I don't want to litter hasNextPriv() with try-catch blocks.
#Override
public boolean hasNext()
{
try {
return hasNextPriv();
} catch (XMLStreamException e) {
e.printStackTrace();
try {
reader.close();
} catch (XMLStreamException e1) {
e1.printStackTrace();
}
}
return false;
}
Questions:
Is there a better way to do this?
What would be a good name for the private method hasNextPriv()?
Another way to handle exceptions would be to extract each part that throws exception in a small pure function that properly handles each exception. And then construct final result composing those functions.
Optional<Resource> open() {
try{
//...
return Optional.of(resource);
} catch {
//....
return Optional.empty();
}
}
Optional<Value> read(Resource resource) {
try{
//...
return Optional.of(resource.value);
} catch {
//....
return Optional.empty();
}
}
boolean hasNext() {
open().flatMap(this::read).isPresent();
}
There is no need to return Optional everywhere. Usually there is some dummy value like in Null Object Pattern
Another pattern is to wrap a function execution in object that produces either result or error value. In library javaslang it looks like
return Try.of(this::hasNextPriv)
.recover(x -> Match(x).of(
Case(instanceOf(Exception_1.class), /*handle exception*/),
Case(instanceOf(Exception_2.class), ...)))
.getOrElse(false);
Try object is similar to java 8 Optional but instead of holding present value or missing value Try contains value of either success or failure.
Regarding naming hasNextPriv in your case there is specific domain of data structure. Probably you could come up with more specific name like hasMoreNodes or notEmpty etc.
I have the following code:
try {
JSONObject json = new JSONObject(data);
...
} catch(JSONException ex) {
if(LOGS_ON) Log.e(TAG, "Could not save data.", ex);
}
It throws an exception, although the json string passed in is pretty valid. The exception is the following:
org.json.JSONException: Value {"ShopId3Digit":"ww0","ServerTime":1426695017191,"SMSTelephone":"2104851130","SendPODAgain":true,"SendLocationAgain":true,"IsHUB":false,"AllowReceiptsAndDeliveries":true} of type java.lang.String cannot be converted to JSONObject
Do you see something wrong with the json data I'm passing in?
BTW this is the string as seen in Eclipse watch:
"{\"ShopId3Digit\":\"ww0\",\"ServerTime\":1426695017191,\"SMSTelephone\":\"2104851130\",\"SendPODAgain\":true,\"SendLocationAgain\":true,\"IsHUB\":false,\"AllowReceiptsAndDeliveries\":true}"
Here's a working version
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
String data = "{\"ShopId3Digit\":\"ww0\",\"ServerTime\":1426695017191,\"SMSTelephone\":\"2104851130\",\"SendPODAgain\":true,\"SendLocationAgain\":true,\"IsHUB\":false,\"AllowReceiptsAndDeliveries\":true}";
try {
JSONObject json = new JSONObject(data);
System.out.println("Success: json = ");
System.out.println(json.toString(2));
} catch(JSONException ex) {
System.out.println("Error: " + ex);
}
}
}
(using the most recent version available at https://github.com/douglascrockford/JSON-java). I have tested this code, it compiles and successfully outputs
Success: json =
{
"IsHUB": false,
"SMSTelephone": "2104851130",
"AllowReceiptsAndDeliveries": true,
"SendPODAgain": true,
"SendLocationAgain": true,
"ShopId3Digit": "ww0",
"ServerTime": 1426695017191
}
Therefore, the error seems to be not with the json data.
It was my mistake after all. I obtain the data from a .NET program through Newtonsoft serializer. By mistake I was serializing the already serialized object resulting in just a string. The starting and ending quotes in the watch in Eclipse are actually part of the value.
Thank you godfatherofpolka for the effort you went through.