Convert String to JSONArray (or any array) - java

Im trying to parse the following value paramter to a JSONArray (or any other array):
"value":"[{\"fileName\":\"Instructions.docx\",\"filePath\":\"http://someserver/api/files/somefilereference1\"},{\"fileName\":\"Sailing plan.docx\",\"filePath\":\"http://someservert/api/files/somefilereference2\"}]"
As you can see I get the "value" as a string instead of a real array. How can I parse this?
I have tried parsing it to both JSONObject and JSONArray with no success.
Any suggestions?

Ah - I figured it out (feels dumb):
String clean = propertyObject.getString("value").replaceAll("\\\\", "");
JSONArray docArray = new JSONArray(clean);

Related

GSON - convert a string into a JsonArray

I am trying to convert a string into a JsonArray. So far I have tried to do the following:
Gson().toJson(string)
Gson().toJsonTree(string)
both throw an exception saying that the argument is not a JsonArray.
Here is the string, as you can see it is a JsonArray:
"[{\"match\":{\"id\":92757102,\"tournament_id\":3666234,\"state\":\"open\",\"player1_id\":58602461,\"player2_id\":58602459,\"player1_prereq_match_id\":null,\"player2_prereq_match_id\":null,\"player1_is_prereq_match_loser\":false,\"player2_is_prereq_match_loser\":false,\"winner_id\":null,\"loser_id\":null,\"started_at\":\"2017-07-17T19:10:07.588-04:00\",\"created_at\":\"2017-07-17T19:10:07.476-04:00\",\"updated_at\":\"2017-07-17T19:10:07.588-04:00\",\"identifier\":\"A\",\"has_attachment\":false,\"round\":1,\"player1_votes\":null,\"player2_votes\":null,\"group_id\":null,\"attachment_count\":null,\"scheduled_time\":null,\"location\":null,\"underway_at\":null,\"optional\":false,\"rushb_id\":null,\"completed_at\":null,\"suggested_play_order\":1,\"prerequisite_match_ids_csv\":\"\",\"scores_csv\":\"\"}}]"
JsonArray data = (JsonArray) JsonParser.parseString(str);
Gson().fromJson(string, JsonArray::class.java)
toJson() renders a json object as a string (of json).
You want the fromJson() method, which converts a string to a json object.
Try:
new Gson().fromJson(string, JsonArray.class)

Add double quotes to some part of a dynamic string

I have a String. I am converting to JSonObject then to JSONArray. But the string is not a perfect JSONObject. I am trying to convert it to a perfect JSONOBject by adding double quotes to ids and States but i am not sure how to do that. Need some suggestions please.
String jsonString = "{
\"userDetails\": {
ids: [\"1\", \"2\"],
States: [\"TX\", \"PA\"]
}
}";
JSONObject obj = new JSONObject(jsonString);
JSONObject obj1 = new JSONObject("userDetails");
String array = obj1.getJSONArray("HE_SUBJECT").toString();
But here its not a perfect JSONObject as ids and States doesnt have the double Quotes. Here i have the string directly but i will be getting the string dynamically. So not sure how i can add double quotes after i can get the jsonString. Need some help please.
just use online http://www.freeformatter.com/java-dotnet-escape.html , just paste your string it will give string in correct escaped format.
Not sure if this is a good way but i am replacing ids with "ids" like:
jsonString.replace("ids","\"ids\"");

JSON Exception String cannot be converted to JSON Object

I am trying to parse json and running into a small problem.
my json string looks like this:
String json =
[
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}",
"{caption=adsf, url=/storage/emulated/0/DCIM/Camera/20140330_103412.jpg}"
]
and my code so far looks like this:
try {
JSONArray jsonObj = new JSONArray(json);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String img = c.getString("url");
String cap = c.getString("caption");
But its throwing an exception type java.lang.String cannot be converted to JSONObject
What am I doing wrong?
EDIT
If its helpful to anyone, I ended up using GSON to get my json in the correct expected format like this:
Gson gson = new Gson();
String json = gson.toJson(mylist);
Your JSON array contains elements like
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}"
which is a String not a JSON object. You can't therefore try to retrieve it as a JSONObject.
Seems like you're getting JSON that isn't in the format you expected. Even if you got rid of the "" around it, it still wouldn't be valid JSON, so I don't understand its purpose enough to help you.

Parsing JSON server response into JSON Array

I am using Java to parse a JSON response from a server. My end goal is to have the data from results in an Array. Currently I am using this to try and get the results:
JSONArray jArray = myResponse.getJSONArray("results");
This code fails because it is looking for an array of objects, rather than an array of strings:
org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject
This is my server's JSON Response:
{
status: "OK",
results: [
"blah",
"bleh",
"blah"
]
}
Is there a simple way to get the "results" value into an array? Or should I just write my own parser.
Thanks
---------- UPDATE ----------
Looks like my problem was actually occuring somewhere else, and not where the JSON attribute "results" was being converted into a JSONArray.
Sorry and thanks for the answers, they helped me realize I was looking in the wrong spot.
This should be it. So you're probably trying to get JSONObject instead of String inside the results aarray.
JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
String resultString = resultsArray.getString(i);
As you will probably have more properties, than only the String[] result, I recommend to define a DTO like this:
public class Dto {
//of course you should have private fields and public setters/getters, but this is only a sample
public String status;
public List<String> results;//this can be also an array
}
And then in your code:
ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need

Split JSON string into two variables

I have a JSON/string/array, not sure what it is now as it’s been through a spinner and is now in a String variable, it was JSON. It looks like this: {“BusName”:”Joe”,”BusPhone”:”1234567890”} what I want to do is split it into two variables, (buiessname = BusName and businessphone = BusPhone), and also remove all the {}, ” and :’s.
I could use split and replace but it would be a messy function, is there some kind of Java/JSON function that can handle it for me??? How would you guys go about it???
Cheers,
Mike.
You can use JSONObject to parse the JSON String into a real object.
String jsonStr = "{\“BusName\”:\”Joe\”,\”BusPhone\”:\”1234567890\”}";
JSONObject myJsonObj = new JSONObject(jsonStr);
String busName = myJsonObj.getString("BusName");
String busPhone = myJSONObj.getString("BusPhone");
I'd suggest using json-simple to parse the JSON data, rather than trying to directly manipulate the string yourself. For example, you might do:
JSONObject data = (JSONObject)JSONValue.parse(text);
String businessName = (String)data.get("BusName");
String businessPhone = (String)data.get("BusPhone");
You can find more examples here: http://code.google.com/p/json-simple/wiki/DecodingExamples.

Categories

Resources