Below is my JSON:
{
"-5": [
"15:D1_CHANNEL_ID_SK",
"23:D1_CALL_BEGIN_DATE",
"87:D1_CELL_ID"
],
"-4": [
"31:I_RECHARGE_AMOUNT",
"59:I_INBUNDLED_UNIT",
"60:I_DAY_NIGHT_FLAG",
"53:PD_UPSELL_PACK_ID",
"146:AON"
]
}
In the above Json, the key is also a variable (it is not constant). Because of that I'm not able to parse the json using mapper.readValue().
Im assuming that by mapper.readValue(), you're trying to read a string value into a map like structure (can be a POJO or a HashMap) with the help of an ObjectMapper.
The following code reads from the string and converts it into a Map<String,Object>.
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String data = "{\n" + " \"-5\": [\n" + " \"15:D1_CHANNEL_ID_SK\",\n" + " \"23:D1_CALL_BEGIN_DATE\",\n" + " \"87:D1_CELL_ID\"\n" + " ],\n" + " \"-4\": [\n" + " \"31:I_RECHARGE_AMOUNT\",\n" + " \"59:I_INBUNDLED_UNIT\",\n" + " \"60:I_DAY_NIGHT_FLAG\",\n" + " \"53:PD_UPSELL_PACK_ID\",\n" + " \"146:AON\"\n" + " ]\n" + "}";
final Map<String, Object> response = objectMapper
.readValue(data, objectMapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class));
}
Of-course, the value type in the map can be an object too. In that case, the code might look like this
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String data = "{\n" + " \"-5\": [\n" + " \"15:D1_CHANNEL_ID_SK\",\n" + " \"23:D1_CALL_BEGIN_DATE\",\n" + " \"87:D1_CELL_ID\"\n" + " ],\n" + " \"-4\": [\n" + " \"31:I_RECHARGE_AMOUNT\",\n" + " \"59:I_INBUNDLED_UNIT\",\n" + " \"60:I_DAY_NIGHT_FLAG\",\n" + " \"53:PD_UPSELL_PACK_ID\",\n" + " \"146:AON\"\n" + " ]\n" + "}";
final Map<String, Your Class Name> response = objectMapper
.readValue(data, objectMapper.getTypeFactory().constructMapType(Map.class, String.class, <Your Class Name>.class));
}
It is also possible to convert the value type to another container based type (like a List), which I leave for your exploration.
Related
I am requesting via OKHttpClient data from my api, and im trying with an getAll() to split up the JSON response into my objects i need.
Here is an example for my response i get:
[
{
"value":"data",
"id":5
},
{
"value":"data",
"id":6
},
{
"value":"data",
"id":7
},
{
"value":"data",
"id":8
},
{
"value":"data",
"id":9
},
{
"value":"value",
"id":10
}
]
I believe you can use GSON in Android, so kindly see the code below:
static class SimpleExample{
private String value;
private Integer id;
}
public static void main(String[] args){
String json = "[{\n"
+ " \"value\":\"data\",\n"
+ " \"id\":5\n"
+ " },\n"
+ " {\n"
+ " \"value\":\"data\",\n"
+ " \"id\":6\n"
+ " },\n"
+ " {\n"
+ " \"value\":\"data\",\n"
+ " \"id\":7\n"
+ " },\n"
+ " {\n"
+ " \"value\":\"data\",\n"
+ " \"id\":8\n"
+ " },\n"
+ " {\n"
+ " \"value\":\"data\",\n"
+ " \"id\":9\n"
+ " },\n"
+ " {\n"
+ " \"value\":\"value\",\n"
+ " \"id\":10\n"
+ " }\n"
+ "]";
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
SimpleExample[] allObjects = gson.fromJson(json, SimpleExample[].class);
System.out.println(allObjects.length);
}
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
I got this response from RapidAPI, As you see in the picture the name indicated by the red vector
is without quotes. I searched for that and I found that is called Relaxed JSON, but I didn't find how to parse this type using Java language.
This works for me
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
String text = "{\n" +
" \"array\": [\n" +
" {\n" +
" 0: {\n" +
" \"id\": 1\n" +
" }\n" +
" },\n" +
" {\n" +
" 1: {\n" +
" \"id\": 2\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
JsonParser parser = new JsonFactory()
.createParser(text)
.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
JsonNode root = new ObjectMapper().readTree(parser);
System.out.println(root);
Result
{"array":[{"0":{"id":1}},{"1":{"id":2}}]}
It's nothing but that 0 is indicating the first value inside the quotes array. Quotes is an array with the 7 objects values. You can access them or get each value from an array using the org.json library.
import org.json.*;
JSONArray arr = obj.getJSONArray("quotes");
for (int i = 0; i < arr.length(); i++)
{
String exchange = arr.getJSONObject(i).getString("exchange");
String shortname = arr.getJSONObject(i).getString("shortname");
.
.
.
// And so on...
}
How can I deserialize multiple objects with same structure but different variable name using object mapper?
{
"id":"A0D-29G3-03",
"a":{
"flag":"NORMAL",
"date":"..."
},
"b":{
"flag":"NORMAL",
"date":"..."
}
}
I'll have more objects than A and B. This is just an example. How can I deserialize multiple objects(using ObjectMapper) with same structure but different class name? Without creating one pojo for each class.....
... different class name
a and b are not different class names, are they? They are different fields which can share the same class. You can use one single class (Abc in the example) for fields a, b, etc.
Does this work for you?
#Setter
#Getter
#ToString
#JsonIgnoreProperties(ignoreUnknown = true)
public static class AbcWrapper {
private String id;
#JsonAnySetter
Map<String, Abc> abc = new LinkedHashMap<>();
}
#Setter
#Getter
#ToString
public static class Abc {
private String flag;
private String date;
}
public static void main(String[] args) throws IOException {
String json = "{ " +
" \"id\":\"A0D-29G3-03\"," +
" \"a\":{ " +
" \"flag\":\"NORMAL\"," +
" \"date\":\"...\"" +
" }," +
" \"a1\":{ " +
" \"flag\":\"NORMAL\"," +
" \"date\":\"...\"" +
" }," +
" \"a2\":{ " +
" \"flag\":\"NORMAL\"," +
" \"date\":\"...\"" +
" }," +
" \"a3\":{ " +
" \"flag\":\"NORMAL\"," +
" \"date\":\"...\"" +
" }," +
" \"b\":{ " +
" \"flag\":\"NORMAL\"," +
" \"date\":\"...\"" +
" }" +
"}";
ObjectMapper mapper = new ObjectMapper();
final AbcWrapper abcWrapper = mapper.readValue(json.getBytes(), AbcWrapper.class);
System.out.println(abcWrapper);
}
I used lombok annotations #Setter, #Getter, #ToString in the example. You can replace them with setters/getters if you don't want to use lombok.
Hello I am new in Java and I have a question.
I am using a package to parse JSON Markups but the following problem is this:
{
"example": {
"subThing": "value"
},
"anotherThing" : 0
...
}
if I call MyClass.getString("example").getString("subThing"); then I am getting the value of subThing.
I want to call these getString() so often as possible ina for loop programmatically with index variable. But I don't know how to do.
for(int i = 0; i > getCurrentState(); i++) {
//Here I want to call getString();
//I want in round loop to call getString();
//In second round loop to call getString().getString();
}
Sorry I just started using java 1 week ago.
edit:
I mean how to call get() and/or getString() programmatically in for loop?
I'm not sure if I understand you correctly, but you may use the following technique here:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class App
{
public static void main( String[] args ) throws JSONException {
JSONObject newObj = new JSONObject("{" +
"\"data\": [\n" +
" {\n" +
"\"id\": 1,\n" +
" \"userId\": 1,\n" +
" \"name\": \"ABC\",\n" +
" \"modified\": \"2014-12-04\",\n" +
" \"created\": \"2014-12-04\",\n" +
" \"items\": [\n" +
" {\n" +
" \"email\": \"abc#gmail.com\",\n" +
" \"links\": [\n" +
" {\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"\n" +
"}");
JSONArray items = newObj.getJSONArray("data");
for (int it = 0; it < items.length(); it++) {
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
JSONArray item = contactItem.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
String email = item.getJSONObject(i).getString("email");
System.out.println(email);
}
System.out.println("Name----------" + userName);
}
}
}
or even better and simpler is to use JsonPath
For your json is would be smth like this
String substring = JsonPath.parse(json).read("$.example.subThing", String.class);
String anotherstring = JsonPath.parse(json).read("$.anotherThing", String.class);
I have a JSON file, as String:
String compString = "{\n" +
" \"Component\": {\n" +
" \"name\": \"Application\",\n" +
" \"environment\": \"QA\",\n" +
" \"hosts\": [\n" +
" \"box1\",\n" +
" \"box2\"\n" +
" ],\n" +
" \"directories\": [\n" +
" \"/path/to/dir1/\",\n" +
" \"/path/to/dir2/\",\n" +
" \"/path/to/dir1/subdir/\",\n" +
" ]\n" +
" }\n" +
" }";
I have a bean representing it (correct if incorrectly)
public class Component {
String name;
String environment;
List<String> hosts = new ArrayList<String>();
List<String> directories = new ArrayList<String>();
// standard getters and setters
}
I am trying to feed this String to this class by:
Gson gson = new Gson();
Component component = gson.fromJson(compString, Component.class);
System.out.println(component.getName());
Above does not work. (I am getting null back, as if Component's name value is never set)
What am i missing please?
In fact, you have to remove the enclosing class from Json.
Indeed, JSON begins with the content of the enclosing class.
So your JSON would be:
String compString = "{\n" +
" \"name\": \"Application\",\n" +
" \"environment\": \"QA\",\n" +
" \"hosts\": [\n" +
" \"box1\",\n" +
" \"box2\"\n" +
" ],\n" +
" \"directories\": [\n" +
" \"/path/to/dir1/\",\n" +
" \"/path/to/dir2/\",\n" +
" \"/path/to/dir1/subdir/\",\n" +
" ]\n" +
" }\n";
String compString =
" {\n" +
" \"name\": \"Application\",\n" +
" \"environment\": \"QA\",\n" +
" \"hosts\": [\n" +
" \"box1\",\n" +
" \"box2\"\n" +
" ],\n" +
" \"directories\": [\n" +
" \"/path/to/dir1/\",\n" +
" \"/path/to/dir2/\",\n" +
" \"/path/to/dir1/subdir/\",\n" +
" ]}" ;
I think you should read more about json, I have removed something in your json string and then success.