I have a JSON string, how can I parse it and just get the valueString in java?
{
"resourceType": "Bundle",
"id": "0",
"entry": [
{
"resource": {
"resourceType": "Basic",
"extension": [
{
"url": "http://ith.sahra.com/extensions#uploadid",
"valueString": "1589355494289_655"
}
]
}
}
]
}
This is my code, I tried to call extension I got null but I got response while calling entry
public static String ParsingValue(String valuepass) throws org.json.simple.parser.ParseException{
Object obj = new JSONParser().parse(valuepass);
JSONObject jo = (JSONObject) obj;
//JSONArray msg = (JSONArray) jo.getClass();
JSONArray result = (JSONArray) jo.get("entry");
}
The easiest way to parse a string through Jackson parser
Eg:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"anshul\",\"age\":29}";
Map<String, Object> map = mapper.readValue(json, Map.class);
Try this, it should solve your problem.
Related
Below Json I want to get only first mail value (abc#test.com) using java. Please anybody can suggest how do I extract exact value from below Json. Thanks in advance.
{
"profiles": [
{
"userId": "1234",
"content": {
"address": {
"business": {
"country": "IN",
"locality": "Chennai",
}
},
"name": {
"first": "abc",
"last": "abc"
},
"mail": [
"abc#test.com",
"xyz#test.com"
]
}
}
]
}
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) throws JSONException {
String jsonstring = "{\"profiles\":[{\"userId\":\"1234\",\"content\":{\"address\":{\"business\":{\"country\":\"IN\",\"locality\":\"Chennai\"}},\"name\":{\"first\":\"abc\",\"last\":\"abc\"},\"mail\":[\"abc#test.com\",\"xyz#test.com\"]}}]}";
System.out.println(jsonstring);
JSONObject jsonObject = new JSONObject(jsonstring);
JSONArray profiles = jsonObject.getJSONArray("profiles");
for (int i = 0; i < profiles.length(); i++) {
JSONObject curProfile= (JSONObject) profiles.get(i);
JSONArray mails= (JSONArray)((JSONObject)curProfile.get("content")).get("mail");
System.out.println(mails.get(0));
}
}
}
as they have already said json standard doesn't impose ordering, so be careful
I can able to get mail by using below code
//root = my json
JsonObject rootobj = root.getAsJsonObject();
JsonArray profilesItems = rootobj.getAsJsonArray("profiles");
JsonObject firstValue = profilesItems.get(0).getAsJsonObject().getAsJsonObject("content");
JsonElement emails = firstValue.get("mail");
String mail = emails.getAsJsonArray().get(0).getAsString();
My Json Array looks like this
[
{
"geoRegion":"101",
"companyName":"101",
"department":"101",
"industry":"101",
"sector":"101",
"formName":"101",
"formType":true,
"fields":[
{
"labelId":"102",
"bizJust":"101"
},
{
"labelId":"103",
"bizJust":"101"
},
{
"labelId":"104",
"bizJust":"101"
},
{
"labelId":"129",
"bizJust":"102"
},
{
"labelId":"128",
"bizJust":"102"
},
{
"labelId":"144",
"bizJust":"102"
},
{
"labelId":"143",
"bizJust":"102"
}
]
}
]
My code is as following:
public Map<String,String> createTransaction(String lang) throws Exception {
Gson gson =new Gson();
JsonObject jsonObj=gson.fromJson(lang, JsonObject.class);//Exception thrown at this line
}
Try to get all the content into the JSON Array instead of the JSON Object.
Change your code from
JsonObject jsonObj=gson.fromJson(lang, JsonObject.class);
to:
JsonArray array = gson.fromJson(lang, JsonArray.class);
String jsonResponse=Utils.getGsonInstance().toJson(Object);
jsonResponse returns :
[
{
"Key":"1",
"Code": "11",
},
{
"key":"2",
"code": "22",
}
]
End result I am looking for is to wrap this JSON-String in another Key E.g.
{
"MainObj":
[
{
"Key":"1",
"Code": "11",
},
{
"key":"2",
"code": "22",
}
]
}
Is there a way I can achieve this using GSON Api ?
I tried ::
JSONObject jsonObject = new JSONObject();
jsonObject.put("MainObj",jsonResponse);
Output I am getting is :
{"MainObj": "[{\"Key\":\"1",\"Code\":\"11\"}, {\"Key\":\"2",\"Code\":\"22\"}]"}
Continue with GSON like :
public class MainObj {
#SerializedName("MainObj")
public List<Key> Main;
public class Key {
#SerializedName("Key")
public String Key;
#SerializedName("code")
public String Code;
}
}
And change
JSONObject jsonObject = new JSONObject();
jsonObject.put("MainObj",jsonResponse);
by
String tmp = new Gson().toJson(new MainObj());
I want to create a JSON Object using String.
Example :
JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}
In order to create the above JSON I am using this.
String message;
JSONObject json = new JSONObject();
json.put("test1", "value1");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 0);
jsonObj.put("name", "testName");
json.put("test2", jsonObj);
message = json.toString();
System.out.println(message);
I want to know how can I create a JSON which has JSON Array in it.
Below is the sample JSON.
{
"name": "student",
"stu": {
"id": 0,
"batch": "batch#"
},
"course": [
{
"information": "test",
"id": "3",
"name": "course1"
}
],
"studentAddress": [
{
"additionalinfo": "test info",
"Address": [
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":36
}
],
"verified": true,
}
]
}
Thanks.
org.json.JSONArray may be what you want.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
String jsonString = "{'element1':'value1','element2':{'id':0,'name':'testName'}}";
JsonObject jsonObject = (JsonObject) JsonParser.parseString(jsonString);
Underscore-java can create json from an object.
import com.github.underscore.U;
String message = U.objectBuilder()
.add("course", U.arrayBuilder()
.add(U.objectBuilder()
.add("id", 3)
.add("information", "test")
.add("name", "course1")
))
.add("name", "student")
.toJson();
System.out.println(message);
// {
// "course": [
// {
// "id": 3,
// "information": "test",
// "name": "course1"
// }
// ],
// "name": "student"
// }
I have String object with template base, something like:
<h1>{{header}}</h1>
{{#bug}}
{{/bug}}
{{#items}}
{{#first}}
<li><strong>{{name}}</strong></li>
{{/first}}
{{#link}}
<li>{{name}}</li>
{{/link}}
{{/items}}
{{#empty}}
<p>The list is empty.</p>
{{/empty}}
I want to pull another String object representing JSONObject and put its fields into template:
{
"header": "Colors",
"items": [
{"name": "red", "first": true, "url": "#Red"},
{"name": "green", "link": true, "url": "#Green"},
{"name": "blue", "link": true, "url": "#Blue"}
],
"empty": false
}
In the end I would get String representing HTML structure:
<h1>Colors</h1>
<li><strong>red</strong></li>
<li>green</li>
<li>blue</li>
I don't want to use any POJOs or Maps - only use standard String objects or alternatively convert second String into JSONObject to use it as a template's context.
Could someone give me any example how to achieve that?
Thanks.
Edit: I don't know anything about template/JSON structure while executing template - I have to play with unknown template/JSON and assume that they are correct.
I couldn't find way to work on pure String objects - I am converting JSONObject to Map to get it working with Mustache. This is code for conversion:
public static Map<String, Object> toMap(JSONObject object) throws JSONException
{
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext())
{
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
public static List toList(JSONArray array) throws JSONException
{
List list = new ArrayList();
for (int i = 0; i < array.length(); i++)
{
list.add(fromJson(array.get(i)));
}
return list;
}
private static Object fromJson(Object json) throws JSONException
{
if (json instanceof JSONObject)
{
return toMap((JSONObject) json);
} else if (json instanceof JSONArray)
{
return toList((JSONArray) json);
} else
{
return json;
}
}
Usage:
mustacheTemplate.execute(JSONUtils.toMap(new JSONObject(myString)));