How to import json strings (not files) into the editor scene?

I hope that clicking on option will get the JSON string from the MySQL database and load it into the scene of the Three.js editor to display the 3D object.

Menubar.Room.js

// Import JSON Object to Editor, not File

	var option = new UIRow();
	option.setClass('option');
	option.setTextContent(strings.getKey('menubar/room/import/object'));
	option.onClick(function () {

		// AJAX 

		var xhr = new XMLHttpRequest();

		xhr.open('post', 'http://192.168.63.100/vdcim/threejsEditor/postThreejsObject.php', true);
		xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

		xhr.onreadystatechange = function () {
			if (xhr.readyState == 4 && xhr.status == 200) {
				console.log(xhr.responseText);

				// var response = JSON.parse(xhr.responseText);
				// console.log("response: " + response);
				var data;

				try {
					// data = JSON.stringify(response['objectjson']);
					// console.log("objectjson: \n" + data);

					//data = JSON.parse(xhr.responseText);
					data = xhr.responseText;

					// var objectloader = new THREE.ObjectLoader();
					// objectloader.parseObject(data);
					editor.loader.loadFile(data);

				} catch (error) {
					alert(error);
					return;
				}

				alert(xhr.responseText + "\n成功,已新增物件到資料庫");
			}
		}

		let objectid = 3;
		let objId = "objectId=" + objectid;
		xhr.send(objId);


	});
	options.add(option);

Error message.

96840100-99934d80-147c-11eb-9a4a-ea345c8eb2d4

This method can only be used if it is called with an instance of File which is not what you have in your code.

If your JSON is in the object/scene format (meaning it is produced by calling Object3D.toJSON()), you can directly use ObjectLoader to deserialize it and add it to the editor’s scene like so:

var loader = new THREE.ObjectLoader();
loader.parse( JSON.parse( data ), function ( result ) {

    if ( result.isScene ) {

        editor.execute( new SetSceneCommand( editor, result ) );

    } else {

        editor.execute( new AddObjectCommand( editor, result ) );

    }

} );
1 Like

Thanks for your reply, it can be loaded and rendered normally after testing.:laughing:

1 Like

@Mugen87 the code you suggested here is great. May I recommend including this in the reference doc for ObjectLoader()? Currently it seems suggest if can only take in a file from a URL.

The documentation of ObjectLoader.parse() states for the first parameter: “The JSON source to parse.”

How would you rewrite the description? Notice that the URL is only required in ObjectLoader.load(). ObjectLoader.parse() accepts a JSON object.

Oh I see, I was reading the doc wrong, I’m sorry about that. Thanks for your response.