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...
}
Related
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.
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 need to create and update index mapping using jest and transport client , but when i try with this tutorial https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-admin-indices.html#java-admin-indices-create-index-settings
i have this problem:
Multiple markers at this line
- Syntax error on token ")", delete this token
- Syntax error on token ".", # expected after
This is my code:
Client client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
IndicesAdminClient indicesAdminClient = client.admin().indices();
indicesAdminClient.prepareCreate("calls")
.setSettings(Settings.builder()
.put("index.number_of_shards", 10)
)
.addMapping("call", "{\n" +
" \"properties\": {\n" +
" \"id\": {\n" +
" \"type\": \"string\"},\n" +
" \"number\": {\n" +
" \"type\": \"string\"},\n" +
" \"name\": {\n" +
" \"type\": \"string\"}\n" +
" }\n" +
" }")
.get();
String json = "{" +
"\"id\":\"1\"," +
"\"number\":\"123333333\"," +
"\"name\":\"Sharon Tries Elastic\"" +
"}";
IndexResponse response = client.prepareIndex("calls", "call")
.setSource(json)
.get();
// Index name
String _index = response.getIndex();
// Type name
String _type = response.getType();
// Document ID (generated or not)
String _id = response.getId();
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
}
can help please
thank you
We can surely, define string in Strings.xml & call - in that case the line break is not an issue.
But suppose I want to put it in my java page -- if I put it as follows - it will bring error
String strJson="
{
\"Employee\" :[
{
\"id\":\"01\",
\"name\":\"Gopal Varma\",
\"salary\":\"500000\"
},
{
\"id\":\"02\",
\"name\":\"Sairamkrishna\",
\"salary\":\"500000\"
},
{
\"id\":\"03\",
\"name\":\"Sathish kallakuri\",
\"salary\":\"600000\"
}
]
}";
I can fix the error by making it in a single line
String strJson=" { \"Employee\" :[ { \"id\":\"01\",\"name\":\"Gopal Varma\",\"salary\":\"500000\"},{\"id\":\"02\",\"name\":\"Sairamkrishna\",\"salary\":\"500000\"}, { \"id\":\"03\", \"name\":\"Sathish kallakuri\", \"salary\":\"600000\" } ] }";
But I want to know, instead is there any escape char or something to fix the error.
Java String literals cannot span multiple lines, but you can do this.
String strJson = "{\n" +
" \"Employee\" :[\n" +
" {\n" +
" \"id\":\"01\",\n" +
" \"name\":\"Gopal Varma\",\n" +
" \"salary\":\"500000\"\n" +
" }\n" +
" ]\n" +
"}";
You need to escape the strings properly,
Try this,
String strJson = "{" +
"\"Employee\": [{" +
"\"id\": \"01\"," +
"\"name\": \"Gopal Varma\"," +
"\"salary\": \"500000\"" +
"}, {" +
"\"id\": \"02\"," +
"\"name\": \"Sairamkrishna\"," +
"\"salary\": \"500000\"" +
"}, {" +
"\"id\": \"03\"," +
"\"name\": \"Sathish kallakuri\"," +
"\"salary\": \"600000\"" +
"}]" +
"}";
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.