how do i insert json value into database

srikotesh
srikotesh used Ask the Experts™
on
Hi Experts,
 
 how to insert the below json value into db?
 how to validate is it valid json or not?
 i will get dynamic json values , i mean it is not static it will differ every
 time.
 can some suggest me how to do
 
 {"location":{"value":""},"category":{"value":"33"},"criticality":{"value":"PROD"}}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2015

Commented:
what type of database is it?
Top Expert 2016
Commented:
how to validate is it valid json or not?
With a JSON parser. If it won't parse properly, it's invalid

Use a PreparedStatement to do the insert - it will escape the string correctly

Author

Commented:
mysql
Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

Top Expert 2015

Commented:
In that case I would do what @CEHJ said.

Author

Commented:
To validate json object is valid or not below is the program

package com.howtodoinjava.restful;

import org.json.JSONException;
import org.json.JSONObject;

public class ValidJson {

	public static void main(String[] args) {
		String json = " {\"location\":{\"value\":\"\"},\"category\":{\"value\":\"33\"},\"criticality\":{\"value\":\"PROD\"}}";
		System.out.println(isValidJSONStringArray(json));
	}

	private static boolean isValidJSONStringArray(String requestBody) {
		try {
			new JSONObject(requestBody);
		} catch (JSONException jsonEx) {
			return false;
		}
		return true;
	}

}

Open in new window

Author

Commented:
i have taken my json object as string and inserted in db successfully.
Top Expert 2016

Commented:
That's good though that method name could be more generic - what happens if no array is involved?

Author

Commented:
sorry, I forgot to change method name like is valid json object
If I gave invalid json it will returns false

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial