How to override the 2nd Object JSON with 1st JSON object - java

I have a situation where I need to override 2nd JSON object value to 1st.
JSON original :-
{
"products": {
"productsApp15": {
"status": "active",
"attribute_set": "Apparel",
"name": "productsApp16",
"product_type": "product",
"code": "productsApp16"
}
}
}
My 1st object :-
{
"productsApp15": {
"attribute_set": "Apparel",
"status": "active",
"name": "productsApp16",
"product_type": "product",
"code": "productsApp16"
}
}
My 2nd object :-
{
"attribute_set": "Apparel",
"status": "active",
"name": "productsApp16",
"product_type": "product",
"code": "try"
}
If you see the value of key -> code is updated here. I want this change in my real or 1st JSON object so I can pass it to my Payload
My Code:-
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONObject jsonObject1 = (JSONObject) jsonObject.get("products");
JSONObject jsonObject2 = (JSONObject)jsonObject1.get("productsApp15");
String firstName = (String) jsonObject2.get("code").toString();
System.out.println("The first name is: " + firstName);
jsonObject2.remove("code");
jsonObject2.put("code", "try");
JSONObject jsonObject3 = (JSONObject)jsonObject1.get("productsApp15");
String firstName2 = (String) jsonObject2.get("code").toString();
System.out.println("The first name is: " + jsonObject3);
JSONObject combined = new JSONObject();
combined.put("Object1", jsonObject1);
combined.put("Object2", jsonObject3);
String firstName3 = (String) jsonObject2.get("code").toString();
System.out.println("The first name is: " + combined);
My Main objective :- I am reading a file which contain my JSON, As you can see my object is again inside an another object .
I want to update the value and then want to pass it to payload.
But how to get the original JSON structure with updated value?
Is it possible?

By Constructing the Java classes against the structure that is required in JSON, this can be achieved.
Messing up with JSON with JSON readers and parser is risky.
public class Products{
private List<Product> productsList;
}
public class Product{
private Map<String, ProProps> map = new HashMap<>();
class ProProps{
private String code;
private String name;
...
}
}
This gives you to map the objects and values.
Get the value of product that you want by key and replace the required props that you want.
Though the conversion of Java - Json takes place, there can be many extensions that can happen when you develop.
You can use this example to convert and do the manipulations required.

Related

Java: Gson: fromJson: Get element value

I have a json string as:
string jsonString = "{"Header":{"ID": "103","DateTime": "2020-07-29 09:14:23.802-4:00 1","PlazaID": "01","Lane": "Lane 20","IPAddr": "192.9.0.123"},"Body": {"EventMsg": "Status: Online","EventNum": "99999"}}";
I am trying to get the value if ID from the above json by using Gson and it gives me NullPointerException. My code:
JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class );
//System.out.println("jsonObject: " + jsonObject.toString());
String _ID = jsonObject.get("ID").getAsString();
I am not sure where the error in my code is. Any help is appreciated.
Edit:
As per #Arvind's suggestion, I tried his code and am getting this error:
As per #Arvind's suggestion, this works:
String _ID = jsonObject.get("Header").getAsJsonObject().get("ID").getAsString();
Let's prettify your jsonString first for clarity:
{
"Header": {
"ID": "103",
"DateTime": "2020-07-29 09:14:23.802-4:00 1",
"PlazaID": "01",
"Lane": "Lane 20",
"IPAddr": "192.9.0.123"
},
"Body": {
"EventMsg": "Status: Online",
"EventNum": "99999"
}
}
Notice that "ID" is inside "Header", so you'd have to parse it this way:
String _ID = jsonObject.getJsonObject("Header").get("ID").getAsString();
Also, avoid using get() since there are better convenience methods:
String _ID = jsonObject.getJsonObject("Header").getString("ID");

How to display the suggestion for autocomplete field using json file?

I have this json that has " product code" inside this product code has another jsonobject and string.
What I want is that when I input the "product code" the suggested description will show.
I already get the display for suggested description when I input the product description code but it seems that it displaying in wrong way.
What I mean is that when I type the "product code" "BI" the display for suggested description is like this
{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}
here is my json
{
"BI": {
"desc": {
"MBIK": "MOUNTAIN BIKE",
"FBIK": "FOLDING BIKE",
"EBIK": "E-BIKE",
"OTHER": "OTHER"
},
"brand": {
"GNT": "GIANT",
"TRL": "TREEK",
"CNN": "CNDALE",
"STC": "SANTA",
"SCT": "SCOTT"
},
"category": "BICYCLE & EBIKE STORE"
},
"CA": {
"desc": {
"CARA": "CAR AUDIO",
"CARS": "CAR SPEAKER",
"TIRE": "CAR TIRE",
"OTHER": "OTHER"
},
"brand": {
"AIC": "AICHI",
"BRI": "BRIGDESTONE",
"CON": "CONTINENTAL",
"DUN": "DUNLOP",
"FAL": "FALKEN GR"
}
"category": "CAR ACCESORIES"
},
and so on.. {
}
}
here is the my code to parse my json to my fragment
private void loadLookupCategoryJson() {
mLookupProducts = new ArrayList<>();
mArrayStringLookupProduct = new ArrayList<>();
try {
JSONObject json = new JSONObject(loadLookupBrandJSON());
Iterator<String> keys = json.keys();
while(keys.hasNext()) {
String key = keys.next();
JSONObject obj = (JSONObject) json.get(key);
JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
JSONObject desc = obj.getJSONObject(Keys.CATEGORY_DESC);
String category = obj.getString(Keys.CATEGORY);
LookupProducts lookupProduct = new LookupProducts(key, brand, desc, category);
mLookupProducts.add(lookupProduct);
mArrayStringLookupProduct.add(String.valueOf(brand));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
and here is my to get the brand dynamic field
} else if (format.equalsIgnoreCase(Keys.AUTO_COMPLETE_FIELD)) {
addTextViews(title);
addAutoCompleteField(desc, inputType, title, mKeys.get(i), mArrayStringLookupProduct, maxLength, minLength);
}
I expect the output should be like this
INPUT TEXT: T
SUGGESTED DISPLAY:GIANT
TREEK
SANTA
SCOTT
Display all values with "T"
actual output
INPUT TEXT: BI
SUGGESTED DISPLAY:{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}
In this line of code - mArrayStringLookupProduct.add(String.valueOf(brand));
You are adding whole jsonObject into mArrayStringLookupProduct ArrayList.
You only want JSONObject brand's values in this ArrayList.
You can make the following changes-
JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
JSONObject desc = obj.getJSONObject(Keys.CATEGORY_DESC);
String category = obj.getString(Keys.CATEGORY);
lookupProduct = new LookupProducts(key, brand, desc, category);
mLookupProducts.add(lookupProduct);
// iterate every brand key, fetch its value and add in arrayList
Iterator<String> brandKeys = brand.keys();
while(brandKeys.hasNext()) {
String bKey = brandKeys.next();
mArrayStringLookupProduct.add((String) brand.get(bKey));
}

Parsing and retrieving elements in a JSON Java

JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
Following is the JSON String:
{
"Search": {
"VehicleList": [
{
"sipp": "CDMR",
"name": "Ford Focus",
"price": 157.85,
"supplier": "Hertz",
"rating": 8.9
},
{
"sipp": "FVAR",
"name": "Ford Galaxy",
"price": 706.89,
"supplier": "Hertz",
"rating": 8.9
}
]
}
}
}
Hi, I can iterate over the whole JSON object with my code but right now I want to print out the name of a vehicle and the price of the vehicle individually. Any help would be appreciated, I am a beginner when it comes to working with JSON.
Your JSON is structured like this JsonObject -> JsonArray-> [JsonObject]
With that in mind you can access the name and price with this
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONArray jsonArray = (JSONObject) obj.getJsonArray("VehicleList");
for(JSONObject jsonObject : jsonArray){
System.out.println(jsonObject.getString("name") + " " + jsonObject.getDouble("price"))
}
}
Depending on your import library it may deviate from the above but the concept is the same.
You need to iterate over the json. For example.
$.Search.VehicleList[0].price will give you [157.85]
$.Search.VehicleList[1].price will give you [706.89]
http://www.jsonquerytool.com/ will come handy for you :)

Getting the values from a JSON string in Java using GSON

I hope someone can show me where i'm doing it wrong...
I'm using sendgrid for my email tracking and it is posting a JSON like the following:
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com"
"userid": "1123",
"template": "welcome"
}
]
Now i want to get the value of for example for "timestamp" which is 1337966815 . I've tried the following:
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
String jsonString = jb.toString();
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String timeStam = jsonObject.get(timestamp).toString();
The string of jsonString gives me the following which i think is in the right format:
[ { "email": "john.doe#sendgrid.com", "timestamp": 1337966815, "event": "click", "url": "http://sendgrid.com" "userid": "1123", "template": "welcome" }]
But i'm getting the following error at this line of code - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 52
What am I doing wrong? Is it the format of jsonString that is confusing the JsonObject?
Any help would be very much appreciated.
Kind regards
Francois
The JSON you show in both examples is invalid. There is a comma missing after "url":"http://sendgrid.com"
Ignoring that, the JSON you show is an array of JSON objects, not an object. This is what the [] denotes (correcting the missing comma):
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com",
"userid": "1123",
"template": "welcome"
}
]
If you are not mapping this JSON to a Java POJO, then you would want to use Gson's JsonParser to parse your String to a JsonElement (Note you could even use it to parse directly from the Stream, but this if for how you have your code now).
JsonElement je = new JsonParser().parse(jsonString);
Now you have what's called a "parse tree". This JsonElement is the root. To access it as an array you're going to do:
JsonArray myArray = je.getAsJsonArray();
You only show this array containing one object, but let's say it could have more than one. By iterating through the array you can do:
for (JsonElement e : myArray)
{
// Access the element as a JsonObject
JsonObject jo = e.getAsJsonObject();
// Get the `timestamp` element from the object
// since it's a number, we get it as a JsonPrimitive
JsonPrimitive tsPrimitive = jo.getAsJsonPrimitive("timestamp");
// get the primitive as a Java long
long timestamp = tsPrimitive.getAsLong();
System.out.println("Timestamp: " + timestamp);
}
Realize that Gson primarily is meant for Object Relational Mapping where you want to take that JSON and have it converted to a Java object. This is actually a lot simpler:
public class ResponseObject {
public String email;
public long timestamp;
public String event;
public String url;
public String userid;
public String template;
}
Because you have array of these, you want to use a TypeToken and Type to indicate your JSON is a List of these ResponseObject objects:
Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);

parse json rest response in java

I am trying to parse json output from neo4j in java as:
Object obj = parser.parse(new FileReader("D:\\neo4j.json"));
JSONArray json = (JSONArray) obj;
System.out.println(json.size());
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = (JSONObject) json.get(i);
String data = (String);
jsonObject.get("outgoing_relationships");
String name = (String) jsonObject.get("name");
System.out.println(data);
System.out.println(name);
}
Can somebody help me to get values inside "data" element:
I have json output from neo4j as follows:
[{
"outgoing_relationships": "http://host1.in:7474/db/data/node/133/relationships/out",
"data": {
"MOTHERS_NAME": "PARVEEN BAGEM",
"MOBILE_NO": "9211573758",
"GENDER": "M",
"name": "MOHD",
"TEL_NO": "0120-",
"PINCODE": "110001"
},
"traverse": "http://host1.in:7474/db/data/node/133/traverse/{returnType}",
"all_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/all/{-list|&|types}",
"property": "http://host1.in:7474/db/data/node/133/properties/{key}",
"self": "http://host1.in:7474/db/data/node/133",
"properties": "http://lhost1.in:7474/db/data/node/133/properties",
"outgoing_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/out/{-list|&|types}",
"incoming_relationships": "http://host1.in:7474/db/data/node/133/relationships/in",
"extensions": {
},
"create_relationship": "http://host1.in:7474/db/data/node/133/relationships",
"paged_traverse": "http://host1.in:7474/db/data/node/133/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://host1.in:7474/db/data/node/133/relationships/all",
"incoming_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/in/{-list|&|types}"
}]
Regards,
Jayendra
You can try following way. Inside the for loop get the data node as JSONObject. From that data node you can extract every property. I just extracted mother name from data.
JSONObject data = (JSONObject) jsonObject.get("data");
final String motherName = (String) data.get("MOTHERS_NAME");
What library are you using to parse JSON ? I'd recommend that you use Jackson
For eg: To get the data you read from the file in a Map, you can write a method like this.
#SuppressWarnings("rawtypes")
public static Map toMap(Object object) throws JsonProcessingException{ ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(object, Map.class);
}

Categories