I'm trying to JSON using Gson and recyclerview. My JSON isnt completely valid. In my JSON, the food field has only one of the string quoted leaving the other unquoted. Kindly see my JSON below...
[
{"quantity" = 2,
"price" = 15,
"food" = "Fried" Rice},
{"quantity" = 2,
"price" = 20,
"food" = "Rice" and Stew}
]
You can see that Fried is in quotes and Rice isnt in quotes, likewise the same for Rice and Stew in the other too. Initially it was like this ...
[
{quantity = 2,
price = 15,
food = Fried Rice},
{quantity = 2,
price = 20,
food = Rice and Stew}
]
My activity class code...
Bundle extras = getIntent().getExtras();
if (extras != null) {
String listOfFood = extras.getString("foods");
listOfFood = listOfFood.replaceAll("([\\w]+)[ ]*=", "\"$1\" ="); // to quote before = value
listOfFood = listOfFood.replaceAll("=[ ]*([\\w#\\.]+)", "= \"$1\""); // to quote after = value, add special character as needed to the exclusion list in regex
listOfFood = listOfFood.replaceAll("=[ ]*\"([\\d]+)\"", "= $1"); // to un-quote decimal value
listOfFood = listOfFood.replaceAll("\"true\"", "true"); // to un-quote boolean
listOfFood = listOfFood.replaceAll("\"false\"", "false"); // to un-quote boolean
Log.d(TAG, "onCreate: "+listOfFood);
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<FoodOrder> posts = new ArrayList<FoodOrder>();
posts = Arrays.asList(mGson.fromJson(listOfFood, FoodOrder[].class));
adapter = new RecyclerViewAdapter(FoodsOrderedActivity.this, posts);
recyclerView.setAdapter(adapter);
}
I need the food field that has Fried Rice to be inbetween quotes as one and the same for rice and stew or if theres a workaround, I would like to know.
Thank you
Base on your code. (Try to convert listOfFood to JSON )
I modify 2 lines of your code as bellow
listOfFood = listOfFood.replaceAll("(\\s*)([^{,\\s]+)(\\s*)=","$1\"$2\"$3:"); // to quote before = value and replace = by :
listOfFood = listOfFood.replaceAll("(:\\s*)([^\\s,{}](\\s*[^\\s,{}]+)*)", "$1\"$2\""); // to quote after = value (= now became :)
The json structure should look like as below
[
{
"Key1" : "value1",
"Key2" : "value2",
},
{
"Key1" : "value1",
"Key2" : "value2",
}
]
The json structure should be like this :
[{"quantity" : 2,
"price" : 15,
"food" : "Fried Rice"},
{"quantity" : 2,
"price" : 20,
"food" : "Rice and Stew"}]
Related
I'm using Jackson to convert objects include Array object to application.properties file but the result when convert array object look not good as I expected.
This is my code:
JSONSerializer serializer = new JSONSerializer().rootName("application").prettyPrint(false);
String json = serializer.serialize(configDto.getValue());
ObjectMapper om = new ObjectMapper();
JsonNode tree = om.readTree(json);
Properties props;
JavaPropsMapper mapper = new JavaPropsMapper();
props = mapper.writeValueAsProperties(tree);
props.store(new FileOutputStream(file), "");
Input:
{
"nation": [
{
"key": "France"
},
{
"key": "Spain"
},
{
"key": "England"
}
],
"movie": "Avatar 2"
}
Result:
application.nation.1 = France
application.nation.2 = Spain
application.nation.3 = England
application.movie = Avatar 2
Result expect:
application.nation[1] = France
application.nation[2] = Spain
application.nation[3] = England
application.movie = Avatar 2
How I can convert data like result I expect? Sorry for my bad English! Thanks!
Possibly make your nation in your json an array. I'm sorry, I haven't tested it.
{
"nation": ["France", "Spain", "England"],
"movie": "Avatar 2"
}
There is any data structure in java that i can work like a key value array from php or javascript?
$objectKeyTarget = "key2";
$array = array(
"key1": {
"id": 1,
"name" "exemple 1"
},
"key2": {
"id": 2,
"name" "exemple 2"
}
);
$dynamicObject = $array[$objectKeyTarget];
Well you could simply use a Map and a List for that. I'd suggest something like this:
public class Entry {
private int id;
private String name;
...
}
Map<String, List<Entry>> entriesByKey = new HashMap<>;
entriesByKey.put("key1", new Entry(1,"exemple 1"));
entriesByKey.put("key2", new Entry(2,"exemple 2"))
Log.d(..., entriesByKey.get("key2"));
If you are trying to store a JSON-Respone: There is in-built JSONObject in Android, so use that one instead.
The simple way
not_array = {
'Y':'YES',
'N':'NO',
'M': {'MY':'MAYBE YES','MN':'MAYBE NO'}
}
value = 'Y';
result = not_array[value];
console.log(result);
value1 = 'M';
value2 = 'MN';
result1 = not_array[value1][value2];
console.log(result1);
I'm trying to create a JSON document by using Jackson. The hierarchy goes as follows:
Event:
class Event {
private String name = "";
private Set<Integer> admin = new HashSet<>();
private List<House> houseList = new ArrayList<>();
}
House:
class House {
private List<OG> OGList = new ArrayList<>();
private int score = 0;
private String name = "";
}
Group:
class OG {
private int score = 0;
private int id = 0;
}
Every event might comprises of a set number of houses, which in turn comprises of a set number of groups. Each house and group has a score modifier as well.
Currently, this is how I print the JSON document using the pretty print method:
ObjectMapper mapper = new ObjectMapper();
File f = new File("./db/" + dir);
if (f.exists() && !f.isDirectory()) {
return "This event name is taken. Please try again.";
}
try {
mapper.writeValue(f, event);
// Convert object to JSON string and pretty print
String jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(event);
System.out.println(jsonInString);
}
}
The resulting output is pretty ugly:
{
"name" : "test",
"admin" : [ 423766405 ],
"houseList" : [ {
"score" : 0,
"name" : "first",
"oglist" : [ {
"score" : 0,
"id" : 0
}, {
"score" : 0,
"id" : 1
}, {
"score" : 0,
"id" : 2
} ]
..
}
Is there a better way to format the output, for example:
name:
test
admin:
a
b
c
houses:
name:
first
group:
1
..
It appears like you want to output YAML, not JSON.
This answer shows how simple it is to write YAML output to a file using Jackson.
This answer shows how to read a YAML file, modify it's contents, and save it back out again.
I am new to android development and new to JSON. I am using the google maps distance matrix api. I have the JSON download into a JSONObject properly I believe.(I stole the code to do it from another post). However I can not seem to parse the JSON properly. I have been working at this for a few day and am completely stumped. I make the following call to google below
https://maps.googleapis.com/maps/api/distancematrix/json?origins=1600%20pennsylvania%20avenue&destinations=1500%20college%20street&mode=driving&units=imperial
The output is this:
{
"destination_addresses" : [ "1500 College Street, Beaumont, TX 77701, USA" ],
"origin_addresses" : [ "1600 Pennsylvania Avenue, Hagerstown, MD 21742, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,306 mi",
"value" : 2102536
},
"duration" : {
"text" : "18 hours 48 mins",
"value" : 67684
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I have tried:
1.
JSONArray jsonArray = jObject.getJSONArray("rows");
JSONArray routes = jsonArray.getJSONArray(0);
stringBuilder.append(routes.getJSONObject(0).getString("text"));
2.
JSONArray jsonArray = jObject.getJSONArray("rows");
JSONObject routes = jsonArray.getJSONObject(0);
stringBuilder.append(routes.getJSONObject("distance").getString("text"));
3.
JSONArray jsonArray = jObject.getJSONArray("elements"); stringBuilder.append(routes.getJSONObject(0).getString("text"));
I have tried more but those seem to me like they should work. It seemed that to me rows is an array and elements is an array as well. So it would follow that I would need to get rows out of the original JSONObject then get the element array out of the row array then get the distance object out of that array, then finally get the text value and add it to the string builder I created earlier.
Were did I go wrong? thank you in advance for any help.
Here is what worked with me
//httpResponse is the output of google api
JSONObject jsonRespRouteDistance = new JSONObject(httpResponse)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray ("elements")
.getJSONObject(0)
.getJSONObject("distance");
String distance = jsonRespRouteDistance.get("text").toString();
/*
* For distance, below is only partial solution as the
* output to string destination_addr will contain square brackets [] and double codes ""
* Eg. [ "1600 Pennsylvania Avenue, Hagerstown, MD 21742, USA" ]
*
*/
String destination_addr = new JSONObject(httpResponse)
.get("destination_addresses")
.toString();
[UPDATE]
Assuming we have only one destination address and not multiple. A little string manipulation gets us the clean string string without codes " and brackets []
StringBuilder stringBuilderDestinationAddr = new StringBuilder();
for (int i = 0; i < destination_addr.length(); i++)
if (destination_addr.charAt(i) != '[' && destination_addr.charAt(i) != ']' && destination_addr.charAt(i) != '"')
stringBuilderDestinationAddr.append(pickup_addr.destination_addr (i));
String strCleanDestination = stringBuilderDestinationAddr.toString();
I have a JSON file and I do not know how can I parse the part of "coordinates", others done already. It seems null, others seem ok when I try to reach them. I guess, coordinates part is another class defined in cities part. Could you please help me to get coordinates of cities?
I kept my cities in a linkedlist.
"cities" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
}
static List<City> allCities = new LinkedList<City>();
static List<Flight> allFlights = new LinkedList<Flight>();
static JSONArray cities;
static JSONArray flights;
FileReader reader = new FileReader("csair.json");
JSONObject CSAirData = (JSONObject) JSONValue.parse(reader);
cities = (JSONArray) CSAirData.get("cities");
flights = (JSONArray) CSAirData.get("routes");
Assuming "cities" is an attribute of variable myVar, like this
var myVar = {
"cities": [
{
"code": "SCL",
"name": "Santiago",
...
}
]
};
then you could access "coordinates" by doing
myVar.cities[0].coordinates
"cities" corresponds to an array
the first element in the array (index = 0) is an object
that object has an attribute called "coordinates", which references another object
Edit
Now that I see you are using Java code, you just need to transform this syntax into Java.
We know that "cities" is a JSONArray.
JSONObject city = cities.get(0); // Get the first city in the array (index = 0)
JSONObject coordinates = city.getJSONObject("coordinates");
int coordinates_s = coordinates.getInt("S");
int coordinates_w = coordinates.getInt("W");