Java - parse string to Json and convert all number values to int - java

When I parse string:
{"action":"duelInvite","id":"1","matchType":"3"}
to JsonObject in this case all values are strings, but how to create JsonObject, that maps id and matchType to int? Do I have to do it manually, when getting those values? It's easier to .getInt("id") rather than Integer.parseInt(.getString("id"))

When you create a JSON Object from a string, all values become strings within the JSON Object. So you're right, you'll have to do it manually. But instead of parsing every time you want to get the values, just do it once when you create the object.
//create your object from the string
jsonObject = new JSONObject(string);
//set the key "id" to the integer value of the String at key "id"
jsonObject.put("id", Integer.parseInt(jsonObject.get("id")));
//set the key "matchType" to the integer value of the String at key "matchType"
jsonObject.put("matchType", Integer.parseInt(jsonObject.get("matchType")));

Related

how to get a particular field value from map object using java

I am trying to set manufacture price code ,that value is in my map
object but when I want to get getName() from map object I am not able
to get that particular value. If I use
ipcToMFPNameMap.getClass().getName()
this line of code to get particular value I get "java.util.HashMap" in
my manufacture price code filed for your reference I post my code what I tried to get the particular result
private Item getItemManufacturerPriceCodes(Item item) {
List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
List<String> priceCodeList = new ArrayList<String>();
for (ItemPriceCode ipc : itemPriceCodes) {
//get the string value from the list
priceCodeList.add(ipc.getPriceCode());
}
//pass this string value in query
List<ManufacturerPriceCodes>mpc = manufacturerPriceCodesRepository.
findByManufacturerIDAndPriceCodeInAndRecordDeleted(item.getManufacturerID(),priceCodeList,NOT_DELETED);
//Convert list to map
Map<String, ManufacturerPriceCodes> ipcToMFPNameMap = mpc.stream().collect(
Collectors.toMap(ManufacturerPriceCodes :: getPriceCode,Function.identity()));// Object
for (ItemPriceCode ipcs : itemPriceCodes) {
ipcs.setManufacturerPriceCode(ipcToMFPNameMap.getClass().getName());
}
item.getItemPriceCodes()
.removeIf(ipcs -> DELETED.equals(ipcs.getRecordDeleted()));
return item;
}
I got this type of Result
But I want this this type of Result
I get issue exact at this point
ipcs.setManufacturerPriceCode(ipcToMFPNameMap.getClass().getName());
my manufacture price code is a string type
Your Map contains ManufacturerPriceCodes objects keyed on their priceCode which is defined as a String. So you can get the name of an item in the Map as follows (where priceCode is a String).
String manufacturerPriceCodesName = ipcToMFPNameMap.get(priceCode).getName();
The ManufacturerPricesCodes appears to capture the price code as a String but Item has a List<ItemPriceCode>. You'll have to figure out how to map back and forth.

Jackson: can not get String value from JsonNode

I have a root-JsonNode
JsonNode payloadNode;
with the following textValue (log.warn("PAYLOAD_NODE" + payloadNode.textValue());):
{"id":0,"uid":""}
But when I,m trying to get String-value from this node:
JsonNode idNode = payloadNode.get("id");
I receive null
Have a look at this.
Method to use for accessing String values. Does NOT do any conversions for non-String value nodes; for non-String values (ones for which isTextual() returns false) null will be returned. For String values, null is never returned (but empty Strings may be)
As it is a text value it is just a string that has no field "id".
So if you have something like this:
String s = "{\"id\":0,\"uid\":\"\"}";
payloadNode = om.valueToTree(s);
you would get such a log output if your JsonNode was just a string as in my example. You need to read your possible string as a json tree so like:
payloadNode = om.readTree(s);
Doing this will give you "0" for id and null for textValue().

How do you set an integer value with JSONObject in Java?

How do you set the value for a key to an integer using JSONObject in Java?
I can set String values using JSONObject.put(a,b);
However, I am not able to figure out how to use .put() to set integer values. For example:
I want my jsonobject to look like this:
{"age": 35}
instead of
{"age": "35"}.
You can store the integer as an int in the object using put, it is more so when you actually pull and decode the data that you would need to do some conversion.
So we create our JSONObject
JSONObject jsonObj = new JSONObject();
Then we can add our int!
jsonObj.put("age",10);
Now to get it back as an integer we simply need to cast it as an int on decode.
int age = (int) jsonObj.get("age");
It isn't so much how the JSONObject is storing it but more so how you retrieve it.
If you're using org.json library, you just have to do this:
JSONObject myJsonObject = new JSONObject();
myJsonObject.put("myKey", 1);
myJsonObject.put("myOtherKey", new Integer(2));
myJsonObject.put("myAutoCastKey", new Integer(3));
int myValue = myJsonObject.getInt("myKey");
Integer myOtherValue = myJsonObject.get("myOtherKey");
int myAutoCastValue = myJsonObject.get("myAutoCastKey");
Remember that you have others "get" methods, like:
myJsonObject.getDouble("key");
myJsonObject.getLong("key");
myJsonObject.getBigDecimal("key");

converting string into json object

I am getting a string like String s = "abc:xyz". Is there any direct method to convert it into JsonObject having abc as key and xyz as value.
I know there a way by converting string into String s = "{\"abc\":\"xyz\"}" and then I can use JSONObject j =(JSONObject) new JSONParser().parse(s); But I have too large list of string to convert into json object. So i don't want to preprocess to convert into quoted string.
And one more way to split string on : . But i want to know any parser method which convert directly into object. So that i does not have to split. It is also a kind of preprocessing.
If there is any way to convert by passing string to method. please suggest.
It sounds like you just want:
String[] bits = s.split(":");
if (bits.length() != 2) {
// Throw an exception or whatever you want
}
JSONObject json = new JSONObject();
json.put(bits[0], bits[1]);
Split the string on :; use the parts to make your object.

Name/value pair loop of JSON Object with Java & JSNI

With GWT, how would I go about looping through a JSON object or array, which has been returned via a JSNI method, that I could also extract both name and value pairs per loop?
Are you using JavaScriptOverlay types or JSONObject like types?
So in case of JSONObject like types and assuming data is of type JSONObject
you can do following:
json_string = "{'data':{'key':'test','key2':'test3','key3':'test3'}}"
JSONObject json_data = JSONParser.parseLenient(json_string);
JSONObject data = json_data.get("data").isObject();
Set<String> keys = data.keySet();
for (String key : keys)
{
String value = data.get(key).isString().stringValue();
}

Categories

Resources