I been trying to solve this issue for quite a while now but i don't seem to have anymore route to take.
I had some backslash that i managed to remove with replace("\", "") but i still have some Quotation Mark like this one ---> " just in the beginning of my map and I don't have any idea how it gets there.
Here is my code:
public void actionPerformed(ActionEvent e) {
JsonObject obj = new JsonObject();
JsonArray ingredList = new JsonArray();
Map<String, String> ingredientAsMap = new HashMap<>();
JsonArray prepTime = new JsonArray();
Map<String, String> prepTimeAsMap = new HashMap<>();
JsonArray cookTime = new JsonArray();
Map<String, String> cookTimeAsMap = new HashMap<>();
obj.addProperty("Recipe Name", textField1.getText().toString());
for (int r = 0; r < model.getRowCount(); r++) {
ingredientAsMap.put("Ingredient", model.getValueAt(r, 0).toString());
ingredientAsMap.put("Measure", model.getValueAt(r, 1).toString());
ingredientAsMap.put("Quantity", model.getValueAt(r, 2).toString());
ingredList.add(String.valueOf(ingredientAsMap));
}
obj.addProperty("Ingredients Lists", String.valueOf(ingredList));
obj.addProperty("Preparation", editorPane1.getText().toString());
prepTimeAsMap.put("Hours", spinner3.getValue().toString());
prepTimeAsMap.put("Mins", spinner2.getValue().toString());
prepTime.add(String.valueOf(prepTimeAsMap));
obj.addProperty("Preparation Time", String.valueOf(prepTime));
cookTimeAsMap.put("Hours", spinner1.getValue().toString());
cookTimeAsMap.put("Mins", spinner4.getValue().toString());
cookTime.add(String.valueOf(cookTimeAsMap));
obj.addProperty("Cooking Time", String.valueOf(cookTime));
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
String json = gson.toJson(obj).replace("\\", "");
try{
FileWriter writer = new FileWriter(System.getProperty("user.dir") + "\\" + textField1.getText().toString() + ".json");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(json);
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println(json);
//System.out.println(System.getProperty("user.dir") + "\\" + textField1.getText().toString() + ".json");
}
Here is the output I get when my form is filled:
{
"Recipe Name": "Test",
"Ingredients Lists": "["{Ingredient=Ingredient0, Measure=ml, Quantity=0}","{Ingredient=Ingredient1, Measure=ml, Quantity=0}"]",
"Preparation": "This is a test.",
"Preparation Time": "["{Hours=0, Mins=0}"]",
"Cooking Time": "["{Hours=0, Mins=0}"]"
}
Notice the " before the [ in Ingredient List, Preparation Time and Cooking Time. How do I get rid of them?
Thanks in advance!
Your issue starts with lines like these
obj.addProperty("Ingredients Lists", String.valueOf(ingredList));
obj.addProperty("Preparation Time", String.valueOf(prepTime));
For the HashMaps, refer How to convert hashmap to JSON object in Java (not the accepted one, but the Gson answer)
Similarly, for the JSONArray, you don't need to String.value them. Just add directly. From the API, use the add(String name, JsonElement element) method.
obj.add("Preparation Time", prepTime);
Detailed answer
Stop string replacing. Your internal data sets are just not JSON, so you are building that JSON incorrectly.
Notice the syntax highlighting
Invalid
{ "Preparation Time": "["{Hours=0, Mins=0}"]" }
Valid - The inner string is escaped.
{ "Preparation Time": "[\"{Hours=0, Mins=0}\"]" }
Which is essentially seen as this to any JSON parser
{ "Preparation Time": "..." }
You can getString("Preparation Time"), and it returns "[\"{Hours=0, Mins=0}\"]" as a String. If you convert that to a JSONArray, then it's an array of strings. Print the first element, you should only see "{Hours=0, Mins=0}" (quotes are kept), and so you should be replacing the quotes and {} characters, not the backslashes. And you could split on equal signs to get key-values, and etc,etc... but that sounds like a lot of work.
Basically, there are no equal signs in key-value JSON pairs.
{Ingredient=Ingredient0, Measure=ml, Quantity=0}
So, Gson is doing to treat every single one of those keys's values as String type and any quotes or backslashes are going to be unescaped when you print the data, but it is stored in memory escaped.
However you want to parse the extra data is unrelated to JSON parsing, so that is my hint and you can stop scratching your head hopefully.
For what it's worth, here is JSON for that data. So, my suggestion is to fix the model class and pieces of code that generate this data.
{
"Recipe Name": "Test",
"Ingredients Lists": [{
"Ingredient": "Ingredient0",
"Measure": "ml",
"Quantity": 0
}, {
"Ingredient": "Ingredient1",
"Measure": "ml",
"Quantity": 0
}],
"Preparation": "This is a test.",
"Preparation Time": [{
"Hours": 0,
"Mins": 0
}],
"Cooking Time": [{
"Hours": 0,
"Mins": 0
}]
}
Related
I'm trying to create a JSON object that looks like:
{
"values": {
"barcode": "{"title":"611269991000grant"}"
}
}
Note that the value of barcode is only a string. Here's what I'm writing:
// title = 611269991000grant
params = new JSONObject("{\"values\": {\"barcode\":" + "\"{\"title\":\"" + title + "\"}\" } }");
The problem however is that this will throw an exception saying
Unterminated object at character 26 of {"values": {"barcode":"{"title":"611269991000grant"}" } }
Anyone know what i'm doing wrong?
That's invalid JSON. Change
params = new JSONObject("{\"values\": {\"barcode\":" + "\"{\"title\":\"" + title + "\"}\" } }");
to
params = new JSONObject("{\"values\": {\"barcode\":" + "{\"title\":\"" + title + "\"} } }");
So that your JSON would finally be:
{
"values": {
"barcode": {"title":"611269991000grant"}
}
}
If your intent is that the value of barcode is a String representation of a document, and not a document ,then
"{"title":"611269991000grant"}"
is not valid, you either scape the inner double quotes " with \ or you replace the inner double quotes " with single quotes '
{
"values": {
"barcode": "{'title':'611269991000grant'}"
}
}
or
{
"values": {
"barcode": "{\"title\":\"611269991000grant\"}"
}
}
Found a solution to my problem:
String jsonobj = "{\\\"title\\\":\\\"" + title + "\\\"}";
params = new JSONObject("{\"values\": {\"barcode\":\"" + jsonobj + "\"} }");
I needed to double escape because the value of barcode is sent over a stream and I still needed it to be in JSON format. So my program now reads the JSON object as
{"values":{"barcode":"{\"title\":\"611269991000,grant\"}"}}
and the barcode value is sent to the stream and read by the webapp as
{"title":"611269991000,grant"}
pseudo JSON! I forgot to mention that the barcode value can only contain a string, which is why I was trying to do magic.
I am getting response this
{
"success": 1,
"message": "some message",
"data": [
{
"comment_id": "43906",
"comp_id": "116725",
"user_id": "48322",
"agree": "0",
.....
"replies": [....]
},
{
"comment_id": "43905",
"comp_id": "116725",
"user_id": "48248",
"agree": "0",
.......
"replies": [...]
}
]
}
I am to get all response in json array like this
JSONObject js =new JSONObject(response);
routeJsonArray.=js.getJSONArray("data");
But I need to reverse all object which is inside data array .In other word when I get response and print commant_id "43906", "43905",
But I need I reverse that objects so that when I print it first give "43905","43906",
there is solution to iterate from i = routeJsonArray.length; i > 0; i-- But i don't want this.I want to store reverse array in another array ..
I try like this.
String [] routeStationString;
JSONArray localJsonArray = js.getJSONArray("data");
routeStationString = new String[localJsonArray.length()];
int k = 0;
for (int i = localJsonArray.length(); i > 0; i--) {
routeStationString[k++] = localJsonArray.getJSONObject(i);
}
System.out.println(routeStationString);
It gives error.?
My approach would be to create a Java Model representing a comment from your array and then proceed like this.
ArrayList<Comment> mList = new ArrayList<Comment>();
for(int i=0;i<routeJsonArray.length();i++){
//get the jsonobject based on the position
//retrieve its values
//create a new comment object and store it to the mList
}
Collection.reverse(mList);
You typically want to parse this array into a POJO, a model. So the idea would be to get a List<Comment> list for example and then you would be able to reverse that list through Collections.reverse(list) method.
How do you use the data from the JSON array? you still have to iterate it, plus remember the keys and everything. the most typical solution is to parse the JSON data into java objects.
JSONArray toReturn = new JSONArray();
int length = jsonArray.length()-1;
for(int i =length; i >= length;i--){
try {
toReturn.put(jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong", Toast.LENGTH_SHORT).show();
}
}
I want to parse an array from Server but I can't obtain the array
Here is the jsonString Successfully got :
{
"status":"OK",
"message":"this is your start and end coordinates",
"data":"{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
I want the Double Values from data arraylist:
//try/catch
Log.d(TAG, "Passes here");
JSONObject jObject = new JSONObject(jsonString);
JSONArray jData = jObject.getJSONArray("data");
Log.d(TAG, "Not PAASING HERE !!! ");
JSONArray jArrayStart = (JSONArray) jData.get(0);
JSONArray jArrayEnd = (JSONArray) jData.get(1);
latitudeStart = (Double) jArrayStart.get(0);
longtitudeStart = (Double) jArrayEnd.get(1);
latitudeEnd = (Double) jArrayEnd.get(0);
longtitudeEnd = (Double) jArrayEnd.get(1);
What you're trying to parse, is a string.
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": "{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
So it works like this:
//first, retrieve the data from the response JSON Object from the server
JSONObject response = new JSONObject(jsonString);
String status = response.getString("status");
String message = response.getString("message");
//Note this: "data" is a string as well, but we'll have to parse that later.
String data = response.getString("data");
//get the doubles from the arrays from the "data" component.
JSONObject dataObject = new JSONObject(data);
JSONArray start = dataObject.getJSONArray("start");
JSONArray end = dataObject.getJSONArray("end");
for (int i = 0; i < start.length(); i++) {
String value = start.getString(i);
//do something with the start String (parse to double first)
}
for (int i = 0; i < end.length(); i++) {
String value = end.getString(i);
//do something with end String (parse to double first)
}
So data is actually a String, but represents a JSONObject (which you'll have to parse), which, in its turn, contains two JSONArrays.
If data was a JSONObject instead of a String, the JSON would have looked like this:
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": {
"start": [
"35.778763",
"51.427360"
],
"end": [
"35.768779", //note that in your example, this quote is missing (first quote on next line too)
"51.415002"
]
}
}
The value of data is not a JSONArray its JSONObject
Explanation
JSONObject will be surrounded by {}
JSONArray will be surrounded by []
data is not an array, it is a json object and therefore you can not access it the way you are doing.
If you want to fetch start array from json object "data" then use below
jObject.optJSONObject("data").optJSONArray("start");
same thing can be used to retrieve "end" json array.
then use optJSONObject() and/or optString() API to retrieve required value from json array.
I need a help... I have a php file which returns me two json Arrays which are as follows:
[{ "id":"1",
"item":"hammers",
"aisle":"20"
}
{ "id":"1",
"item":"hammers",
"aisle":"20"
}]
[{ "id":"1",
"itemFound":"Your item #item",
"ThankYou":"and Thank You for using Txtcore!"
}]
Now, I want to get the second array items in Android. I have the following code now which is like :
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(jsonObject.getString("item"));
aisles.add(""+jsonObject.getString("item");
}
But obviously, that returns me the objects from the first array. I want to get the Objects from the second array. Any suggestions.
Your JSON is not valid but u can get your element as follows. It is a solution from many(just a worlaround).
String str = "YOUR_JSON_RESPONSE";
String array[] = str.split("\\[\\{");//
try {
JSONArray jsonArray=new JSONArray("[{" + array[2]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I guess you'll have to do some dirty coding because the data return by the PHP page is not well formed JSON.
You could try to transform the JSON data to:
{ "data" : [ <array_1>, <array_2> ]} And then use the JSON parser. A simple replacement with a regexp could be fine.
result.replaceAll("\\]\\s*\\[", "], [");
StringBuffer buffer=new StringBuffer(result);
buffer.insert(0,"{ \"data\": ");
buffer.append(" }");
JSONObject jsonObject = new JSONObject(buffer.toString());
JSONArray secondArray= jsonObject.getJSONArray("data").getJSONArray(1);
The creation of a valid JSON string can be done in one step with the appropriate regexp. Hope some one with more time can post it here.
I have a JSON Object of the following and I need to parse the path strings inside the web array into an new JSON array.
"taxonomy": {
"source": {
"master": {
"_id": "5000",
"path": "/Appliances/Refrigerators/French Door Bottom Freezers"
},
"web": [
{
"_id": "6686",
"path": "/Appliances/Refrigerators/French Door Bottom Freezers"
},
{
"_id": "7686",
"path": "/Appliances/Refrigerators/Bottom Freezers"
}
],
},
},
I have written till this but I'm not sure how to get all the path inside the web array.
JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy");
if(jsonTaxonomy!=null)
{
if(!jsonTaxonomy.isNull("source"))
{
JSONObject jsonTaxonomySource= jsonTaxonomy.optJSONObject("source");
if(!jsonTaxonomySource.isNull("web"))
{
JSONArray jsonTaxonomySourceWeb= jsonTaxonomySource.optJSONArray("web");
if(jsonTaxonomySourceWeb!=null && jsonTaxonomySourceWeb.length()>0)
{
//Got inside the array
}
}
}
}
Without providing you with a full answer, I'm convinced you'll be able to find your answer by debugging this method and stopping it at the most inner if(). You'll be able to of what jsonTaxonomySearsWeb consists and thus how to get its values.
Modify your code to something like this:-
JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy");
if(jsonTaxonomy!=null)
{
JSONObject jsonTaxonomySource = jsonTaxonomy.optJSONObject("source");
if(jsonTaxonomySource!=null)
{
JSONArray jsonTaxonomySearsWeb= jsonTaxonomySource.optJSONArray("web");
if(jsonTaxonomySearsWeb!=null)
{
// Traverse through your JSONArray and get each Object & extract path from it.
}
}
}
I am bit unclear about the question. But As per my understanding you want to parse the JSON if you want to do that in java then you can use GSON jar from google...you can also check simple example here Gson handle object or array
Try like this...
groups = json.getJSONArray(TAG_GROUP);
System.out.println("Result Success+++"+groups);
for (int i = 0; i < groups.length(); i++) {
JSONObject c = groups.getJSONObject(i);
String source = c.getString(TAG_SOURCE);
System.out.println("Checking ::"+source);
String lname = c.getString(TAG_PATH);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SOURCE, source);
map.put(TAG_PATH,path);
weblist.add(map); //weblist is your arraylist for both values
webpathlist.add(path); //webpathlist is your arraylist for path
}
List<String> newList = new ArrayList<String>();
newList.addAll(weblist);